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.

1
  • Separately, see also this answer for why you probably don't want to use for ( let i in res){. Commented Jun 3, 2019 at 10:36

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.