我有一个对象(来自MongoDB),看起来像这样:

var test = [
  {
    "_id": "1",
    "childs": [
      {
        "name": "First child",
        "child_id": 1
      },
      {
        "name": "Second child",
        "child_id": 2
      }
    ]
  },
  {
    "_id": "2",
    "childs": [
      {
        "name": "First child",
        "child_id": 1
      }
    ]
  }
];


我试图通过循环,并将每个孩子显示为单独的项目。这就是我的做法:

var response_items = [];

//Process relays as individual devices
test.forEach(function(device) {
    var response_item = {};
    response_item._id = device._id;

    //Process relays as individual devices
    device.childs.forEach(function(child) {
        response_item.name = child.name;
        response_item.child_id = child.child_id;
        //Return devices
        response_items.push(response_item);
    });
});

console.log(response_items);


但是由于某种原因,这是我得到的结果:

Array (3)
{_id: "1", name: "Second child", child_id: 2}
{_id: "1", name: "Second child", child_id: 2}
{_id: "2", name: "First child", child_id: 1}


第三项是正确的,但是第一项和第二项是重复的,我不知道自己在做什么错。

示例:https://jsfiddle.net/om89y661/

最佳答案

var test = [
  {
    "_id": "1",
    "childs": [
      {
        "name": "First child",
        "child_id": 1
      },
      {
        "name": "Second child",
        "child_id": 2
      }
    ]
  },
  {
    "_id": "2",
    "childs": [
      {
        "name": "First child",
        "child_id": 1
      }
    ]
  }
];

var response_items = [];

//Process relays as individual devices
test.forEach(function(device) {

//Process relays as individual devices
device.childs.forEach(function(child) {
                var response_item = {};
	response_item._id = device._id;

	response_item.name = child.name;
	response_item.child_id = child.child_id;
	//Return devices
	response_items.push(response_item);
});

});

console.log(response_items);

关于javascript - 无法在JavaScript中的嵌套对象/数组中正确循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38124468/

10-12 15:11
查看更多