Kshri
Kshri

Reputation: 414

Adding array of objects into single array

I am trying to push array of objects from an existing object to a new array. But only the last value is getting pushed

Ex: Instead of getting 1 2 3 as output, I am getting 3 3 3

var arr=[{'id':'1','name':'xyz'},{'id':'2','name':'pqr'},{'id':'3','name':'mon'}];
var toSend=[];
var obj={'id':""};
for(var i=0;i<arr.length;i++) {
    obj.id = arr[i].id;
  toSend.push(obj);
}

Fiddle link

Upvotes: 3

Views: 423

Answers (4)

Hemadri Dasari
Hemadri Dasari

Reputation: 33974

var variable obj needs to be declared inside for loop

Also stop using var and start using let. The recommendations from ES is to use let rather than using var. because var has window scope whereas let has block level scope

for(let i=0;i<arr.length;i++) {
     let obj= {};
     obj.id = arr[i].id;
     toSend.push(obj);
}

Or you can also use map

 arr.map((data, i) => {
     let obj= {};
     obj.id = data.id;
     toSend.push(obj);
}

Sorry if there are syntax errors because I am answering from mobile :)

Upvotes: 1

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can also use Array.map() with array destructuring:

var arr=[{'id':'1','name':'xyz'},{'id':'2','name':'pqr'},{'id':'3','name':'mon'}];
var toSend = arr.map(({id}) => ({id}));
console.log(toSend);

Upvotes: 1

31piy
31piy

Reputation: 23859

Your code is almost right and it needs the corrections as @Nina already mentioned in her answer.

But if you want a better approach to do this, Array#map is what you need. Here are the benefits it offers:

  1. It implicitly loops over the array. So you don't need to write your own for loop.
  2. It implicitly returns a new object. So you don't need to declare and use new objects in the loop.
  3. It provides more functional approach towards the task you want to do.

var arr = [{
  'id': '1',
  'name': 'xyz'
}, {
  'id': '2',
  'name': 'pqr'
}, {
  'id': '3',
  'name': 'mon'
}];

var toSend = arr.map(item => item.id);
console.log(toSend);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386550

You push the same object reference to the array. By using new objects, all obejcts are different.

var arr = [{ id: '1', name: 'xyz' }, { id: '2', name: 'pqr' }, { id:'3', name: 'mon' }],
    toSend = [],
    obj;

for (var i = 0; i < arr.length; i++) {
    obj = { id: arr[i].id };
    toSend.push(obj);
}

console.log(toSend);

Upvotes: 2

Related Questions