2

I'm trying to store the objects into Javascript array.

var res=[
    {name:'Alex',place:'US',age:20},
    {name:'Jason',place:'Canada',age:25}
  ];

var obj={};
var data=[];

for ( let i in res){
    obj.name=res[i].name;
    obj.place=res[i].place;
    data.push(obj);
 }

console.log(data);

My expected output:

[ 
  {name:'Alex',place:'US'}.
  {name:'Jason',place:'Canada'} 
]

Actual output I got:

[ 
  {name:'Jason',place:'Canada'},
  {name:'Jason',place:'Canada' }
]

Why I'm getting this type of output? I'm noobie.Please help me.

Vasu Ch
  • 185
  • 2
  • 12
  • Separately, see also [this answer](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript/9329476#9329476) for why you probably don't want to use `for ( let i in res){`. – T.J. Crowder Jun 03 '19 at 10:36

3 Answers3

2

You only have one object in memory with your var obj={}; - that line runs once, and creates one object in memory, which you then proceed to mutate on every iteration in the for loop, and push to the array. At the end, the array contains 2 references to the same object.

Create the object inside the loop instead:

for ( let i in res){
    var obj = {};
    obj.name=res[i].name;
    obj.place=res[i].place;
    data.push(obj);
}

You could also consider using .map instead:

const res=[
  {name:'Alex',place:'US',age:20},
  {name:'Jason',place:'Canada',age:25}
];
const data = res.map(({ name, place }) => ({ name, place }));
console.log(data);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

You are basically updating the same object again and again in your loop. You need to have different objects for each loop. Hence, you need to move var obj={} inside the for loop.

var res=[{name:'Alex',place:'US',age:20},{name:'Jason',place:'Canada',age:25}];


var data=[];

for ( let i in res){
    var obj={};
    obj.name=res[i].name;
    obj.place=res[i].place;
    data.push(obj);
}

console.log(data);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
1

Using .map would be much easier

    var res=[
        {name:'Alex',place:'US',age:20},
        {name:'Jason',place:'Canada',age:25}
      ];
    
    var obj={};
    var data = res.map(({ name, place }) => {
      return ({ name, place })
    });
    console.log(data);
Adder
  • 5,708
  • 1
  • 28
  • 56
Anita
  • 476
  • 3
  • 10
  • 24