2

So i have 2 arrays of objects , i want to get the name value from one and assign it to the label and value . This is what i am doing.

let newAreas = [{ label: '', value: '' }];
let areas = [{name: 'Haram', condition: true, counter: 5}, {name: 'Nasr City', condition: false, counter: 3}, {name: 'Faisl', condition: true, counter: 7}];  

i want to get the each name and assign them to label and value so now i loop

areas.map(area => {
      newAreas.map(val => {
        val.label = area.name;
        val.value = area.name;
  });
});

    console.log(newAreas);

but this only gets me the last value what am i doing wrong here ?

7
  • 1
    map does not change the existing array but returns a new one. Commented Feb 10, 2019 at 15:43
  • You want to get a new object with label equal to name and value equal to name from each of the objects in the areas array? Commented Feb 10, 2019 at 15:43
  • Could you write down your desired output ? Commented Feb 10, 2019 at 15:45
  • It's not really what role newAreas plays as an array with one object. Is that just there as a template for the objects you want? Nor is it clear what you need to have two keys with the same value. Commented Feb 10, 2019 at 15:46
  • Try this newAreas.push() Commented Feb 10, 2019 at 15:46

1 Answer 1

3

You only want to use map once, and retrieve the returned value:

const areas = [
  {name: 'Haram', condition: true, counter: 5}, 
  {name: 'Nasr City', condition: false, counter: 3}, 
  {name: 'Faisl', condition: true, counter: 7}
];

const newAreas = areas.map(({name}) => ({label: name, value: name}));

console.log(newAreas);

This makes use of object destructuring.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that did it !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.