0

I am trying to add objects in an array, each array has multiple fields like email and name. The following is how the array looks like. I want to add it to another array.

result = [
  {
    "email": "[email protected]",
    "firstName": "abc"
  },
  {
    "email": "[email protected]",
    "firstName": "def"
  }
]

The following is the logic I'm trying to apply.

var userEmail = ""
var users = [];
var newUser = {'email' : "", 'name' : "", 'type' : 'to'};

for(var i=0; i<result.length; i++){
   userEmail = result[i].email
   //console.log(userEmail);
   newUser.email = result[i].email;
   newUser.name = result[i].firstName; 
   users.push(newUser);
  }

My expected output is this

users = [ { email: '[email protected]', name: 'abc' },
  { email: '[email protected]', name: 'def' } ]

But the output I'm getting is this

[ { email: '[email protected]', name: 'abc' },
  { email: '[email protected]', name: 'abc' } ]

Where am I going wrong?

3 Answers 3

5

You're repeatedly updating a single object with the new values, instead of creating a new object in each iteration. You should have created var newUser = {}; inside the loop.

That said, it would be better to use .map which is the standard function to transmute an array into another array:

var users = result.map(function(r) {
    return { email: r.email, name: r.firstName, type: 'to' };
});

or in ES6 syntax:

let users = result.map(r => ({ email: r.email, name: r.firstName, type: 'to' }));
Sign up to request clarification or add additional context in comments.

4 Comments

How do I create a new object in each iteration
that is it! I think, some more description might be required on this.
Or by using destructuring: result.map(({email, firstName}) => ({email, name: firstName})). Take away in general is to use the higher order functions (map, filter, reduce, ...) to avoid error prone for iterations when transforming data from one form into another.
@dotcs I'm not sure that the destructuring helps much in this particular case
1

You were running into problems with your newUsers object. Since it is an object you are just adding a reference to this object to the users array. When you are changing it agin in the second iteration you are also mutating the original reference. The below snippet should fix the problem.

var userEmail = ""
var users = [];
                          
for(var i=0; i<result.length; i++){
   users.push({
     email: result[i].email,
     name: result[i].firstName,
     type: 'to'
   });
  }

Comments

-1

Try this:

var result = [
  {
    "email": "[email protected]",
    "firstName": "abc"
  },
  {
    "email": "[email protected]",
    "firstName": "def"
  }
];

users = [];

result.forEach(function(obj){
    var newUser = {};
    newUser.email = obj.email;
    newUser.name = obj.firstName
    users.push(newUser)
})

console.log(users)

2 Comments

What is wrong with this approch. can anyone explain this ?
you've used .forEach / push when you should have used .map

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.