最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Pushing Javascript Object Inside An Array Using A For Loop - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 10

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

发布评论

评论列表(0)

  1. 暂无评论