Hi I am trying push a javascript object inside an array in javascript using a for loop to iterate through the data. Here is how my code looks like.
var data = {"up": [{
"name": "jack",
"age" : 10
},
{
"name" : "jhon",
"age" : 12
}]};
var output = {};
var output_data = {
element: []
};
for (var key in data.up) {
output.user_name = data.up[key].name;
output_data.element.push(output);
}
console.log(output_data.element);
However as you can see in the example ,js,console only the second element is name 'jhon' is inserted in both occations. What am I doing wrong here? Please explain.
Hi I am trying push a javascript object inside an array in javascript using a for loop to iterate through the data. Here is how my code looks like.
var data = {"up": [{
"name": "jack",
"age" : 10
},
{
"name" : "jhon",
"age" : 12
}]};
var output = {};
var output_data = {
element: []
};
for (var key in data.up) {
output.user_name = data.up[key].name;
output_data.element.push(output);
}
console.log(output_data.element);
However as you can see in the example http://jsbin./fanazaxoda/edit?html,js,console only the second element is name 'jhon' is inserted in both occations. What am I doing wrong here? Please explain.
Share Improve this question edited Jun 7, 2016 at 5:14 Pranav C Balan 115k25 gold badges171 silver badges195 bronze badges asked Jun 7, 2016 at 5:07 rkshrksh 4,05010 gold badges52 silver badges72 bronze badges 2- what is your expected output ? only name or the entire object? – brk Commented Jun 7, 2016 at 5:11
- You are using the same output object each time. It will break because you will have reference to the same object. – binariedMe Commented Jun 7, 2016 at 5:12
1 Answer
Reset to default 10Move the output initialization inside for loop otherwise it push reference of object each time. Updating it's property may reflect in all array elements since all elements are referring the same object.
var output_data = {
element: []
};
for (var key in data.up) {
var output = {}; // create new empty object on each iteration
output.user_name = data.up[key].name;
output_data.element.push(output);
}
var data = {
"up": [{
"name": "jack",
"age": 10
}, {
"name": "jhon",
"age": 12
}]
};
var output_data = {
element: []
};
for (var key in data.up) {
var output = {};
output.user_name = data.up[key].name;
output_data.element.push(output);
}
console.log(output_data.element);