如何遍历嵌套数据

时间:2018-02-02 12:24:16

标签: javascript loops iteration lodash

我必须遍历一个大型数据集来收集javascript中节点的最后一个子元素。

我需要在子详细信息中找到一组分支代码。 以下是我试图获得的输出:

[1000,1201,1202,2101,3101,3201]



{
  "TITLE": {
    "FirstLevel": {
      "Details": {
        "Code": "01",
      },
      "SecondLevel": [
        {
          "Details": {             
            "Description": "{desc}",          
          },
          "ThirdLevel": {
            "Details": {
              "Code": "01",
            },
            "FourthLevel": [
              {
                "Details": {
                  "Code": "11",
                },
                "Branch": {
                  "Details": {
                    "Code": "1000",
                  }
                }
              },
              {
                "Details": {
                  "Code": "12",
                },
                "Branch": [
                  {
                    "Details": {
                      "Code": "1201",
                    }
                  },
                  {
                    "Details": {
                      "Code": "1202",
                    }
                  }
                ]
              }
            ]
          }
        },
        {
          "Details": {
            "Code": "100",
          },
          "ThirdLevel": [
            {
              "Details": {
                "Code": "02",
              },
              "FourthLevel": {
                "Details": {
                  "Code": "21"
                },
                "Branch": {
                  "Details": {
                    "Code": "2101",
                  }
                }
              }
            },
            {
              "Details": {
                "Code": "03",
              },
              "FourthLevel": [
                {
                  "Details": {
                    "Code": "31",
                  },
                  "Branch": {
                    "Details": {
                      "Code": "3101",
                    }
                  }
                },
                {
                  "Details": {
                    "Code": "32",
                  },
                  "Branch": {
                    "Details": {
                      "Code": "3201",
                    }
                  }
                }
              ]
            }
          ]
        }
      ]
    }
  }
}




我已经查看了更多基本问题的答案,并尝试调整解决方案。

一个这样的解决方案接受id传递,并将根据id更新名称。我想我可以在这里使用类似的地图实现。有一个问题,因为阵列不仅仅有孩子。表示将有子节点的位置。



function update(object, passedId) {

    object.children.map((element, index) => {
        if (element.id === passedId) {
            console.log(index)
            object.children[index].name = "New Name"
        }
        if (element.children != null) { // condition for checking Nesting
            update(element, passedId)
        }
    })

    console.log(object.children)
}

update(obj, "Branch");




接下来我尝试了一种更简单的方法



function getSubItem(obj) {
  for (item in obj) {
    for (subItem in obj[item]) {
      for (subsubItem in obj[subItem]){
      console.log(obj[item][subItem][subsubItem]);
      }
    }
  }
}
getSubItem(obj)




依此类推,在sub子项之后添加sub,但是那种嵌套for循环看起来非常不稳定,而且由于分支可以嵌套在不同的区域,所以它看起来也不可靠。我在这里错过了一个简单的解决方案

3 个答案:

答案 0 :(得分:1)

类似的东西:

function update (data, passedId, acc = []) {
    if (!_.isObject(data)) {
        return acc;
    }

    return _.reduce(_.values(data), (result, item) => {
        result = _.chain(item)
            .get(passedId)
            .thru(val => [val])
            .flatten()
            .compact()
            .map('Details.Code')
            .thru(vals => _.concat(result, vals))
            .value();
       return update(item, passedId, result);
    }, acc);
}

const res = update(data, 'Branch');

答案 1 :(得分:1)

试试这个:

const obj = {
    "TITLE": {
        "FirstLevel": {
            "Details": {
                "Code": "01",
            },
            "SecondLevel": [{
                    "Details": {
                        "Description": "{desc}",
                    },
                    "ThirdLevel": {
                        "Details": {
                            "Code": "01",
                        },
                        "FourthLevel": [{
                                "Details": {
                                    "Code": "11",
                                },
                                "Branch": {
                                    "Details": {
                                        "Code": "1000",
                                    }
                                }
                            },
                            {
                                "Details": {
                                    "Code": "12",
                                },
                                "Branch": [{
                                        "Details": {
                                            "Code": "1201",
                                        }
                                    },
                                    {
                                        "Details": {
                                            "Code": "1202",
                                        }
                                    }
                                ]
                            }
                        ]
                    }
                },
                {
                    "Details": {
                        "Code": "100",
                    },
                    "ThirdLevel": [{
                            "Details": {
                                "Code": "02",
                            },
                            "FourthLevel": {
                                "Details": {
                                    "Code": "21"
                                },
                                "Branch": {
                                    "Details": {
                                        "Code": "2101",
                                    }
                                }
                            }
                        },
                        {
                            "Details": {
                                "Code": "03",
                            },
                            "FourthLevel": [{
                                    "Details": {
                                        "Code": "31",
                                    },
                                    "Branch": {
                                        "Details": {
                                            "Code": "3101",
                                        }
                                    }
                                },
                                {
                                    "Details": {
                                        "Code": "32",
                                    },
                                    "Branch": {
                                        "Details": {
                                            "Code": "3201",
                                        }
                                    }
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    }
};

function transData(data, propertyName, path, result = []) {
	
    if (data instanceof Array) {
        data.forEach(obj => transData(obj, propertyName, path, result));
    } else if (data instanceof Object) {
        let existProperty = Object.keys(data).indexOf(propertyName) > -1;
        if (existProperty) {
            getCode(data[propertyName], path, result);
        } else {
            Object.keys(data).forEach(key => transData(data[key], propertyName, path, result));
        }
    }

    function getCode(data, path, result) {
        if (data instanceof Array) {
            data.forEach(obj => getCode(obj, path, result));
        } else {
            if (typeof path !== 'undefined') {
                result.push(path.split(/\./g).reduce((accumulator, val) => accumulator = accumulator[val], data));
            } else {
                result.push(data);
            }
        }
    }

    return result;
}

console.log(transData(obj, 'Branch', 'Details.Code'));
console.log(transData(obj, 'Branch'));

答案 2 :(得分:0)

从Deepdash(Deep Lodash扩展名)尝试_.eachDeep方法。

这是您的情况: https://codepen.io/yurigor/pen/moMpLV

var res = [];
_.eachDeep(data,function(value,key){
  if(key=="Branch"){
    if(!_.isArray(value)){
      value = [value];
    }
    _.each(value,function(v){
      if(v.Details&&v.Details.Code){
        res.push(v.Details.Code);
      }
    });
  }
});