Reputation: 414
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);
}
Upvotes: 3
Views: 423
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
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
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:
for
loop.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
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