简体   繁体   English

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

[英]Unable to loop through properly in nested object/array in javascript

I have an object(coming from MongoDB), that looks like this: 我有一个对象(来自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
      }
    ]
  }
];

I'm trying to loop through this and display each child as a separate item. 我正在尝试遍历这个并将每个孩子显示为一个单独的项目。 This is how i'm doing it: 这就是我在做的方式:

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

But for some reason this is the result i got: 但由于某种原因,这是我得到的结果:

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}

The third item is correct, however the first and second is duplicated and i have no idea what i'm doing wrong. 第三项是正确的,但第一项和第二项是重复的,我不知道我做错了什么。

Example: https://jsfiddle.net/om89y661/ 示例: 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); 

Use Array.reduce() to flatten your array as below in a pure functional approach: 使用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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM