1
 let personNames = [ { firstName: 'Ben' }, {firstName : 'Bob' } ];
 let details=  { city: 'Dublin' , Country: 'Ireland' } ;
 let nameList = [];
 let nameObj = {};
 for(let name of personNames){
   nameObj = details;
   nameObj['f_name'] = name.firstName;
   nameList.push(nameObj);
 }

expected output :

[ {fname:'Ben', city: 'Dublin' , Country: 'Ireland'}, {fname:'Bob',city: 
'Dublin' , Country: 'Ireland'}]

what I'm getting is:

[ {fname:'Ben', city: 'Dublin' , Country: 'Ireland'}, {fname:'Ben', city: 'Dublin' , Country: 'Ireland'}}]

What am I doing wrong here?

4
  • 5
    Move let nameObj = {}; inside the loop. Commented Feb 13, 2018 at 10:42
  • 1
    you are using the same nameObj reference.. declare inside your for loop Commented Feb 13, 2018 at 10:43
  • @Andy Thanks, it works Commented Feb 13, 2018 at 10:44
  • let nameList = personNames.map(person => ({ fName: person.firstName })) Commented Feb 13, 2018 at 10:46

3 Answers 3

3

What are you doing here is pushing into the array the same reference. You could create each time the nameObj into the for loop in order to have references to different objects in your array.

 let personNames = [ { firstName: 'Ben' }, {firstName : 'Bob' } ];
 let nameList = [];
 for(let name of personNames){
   let nameObj = {};
   nameObj['f_name'] = name.firstName;
   nameList.push(nameObj);
 }
Sign up to request clarification or add additional context in comments.

Comments

1

You can achieve it using Array.map method, which is ES6

const personNames = [{
  firstName: 'Ben',
}, {
  firstName : 'Bob',
}];

const nameList = personNames.map(x => ({
  f_name: x.firstName,
}));
 
 
console.log(nameList);


We are looping through personNames, and for each element in it, we are creating a new object which contains a key named f_name.

Comments

0

nameObj should be inside the for loop

Comments

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.