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

up vote 2 down vote accepted

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);

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);

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);

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 :)

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.