无法在javascript中嵌套对象/数组中正确循环

时间:2016-06-30 13:23:16

标签: javascript arrays loops object foreach

我有一个对象(来自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/

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

使用Array.reduce()以纯粹的功能方法展平您的数组:



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 result = test.reduce(function (accumulator, current) {
  var mappedRes = current.childs.map(function (item) {
    item._id = current._id;
    return item;
  });
  return accumulator.concat(mappedRes);
}, []);

console.log(result);