简体   繁体   English

如何迭代 JSON 对象并在 Javascript 中使用其层次结构动态添加键值对对象?

[英]How to Iterate the JSON object and add a key value pair object dynamically using its hierarchy level in Javascript?

I want this JSON to be iterated and add a key value pair with its level.我希望这个 JSON 被迭代并添加一个带有它的级别的键值对。

For example:例如:

The first level hierarchy should be level 0 and second level should be level 1, and so on.第一级层次结构应为 0 级,第二级应为 1 级,依此类推。

var json = [{
  "name": "parent 1",
  "children": [
    {
      "name": "child 1",
      "children": [
            {
            "name": "child 11"
            }
        ]
    },
    {
      "name": "child 2"
    }
  ]
}];

Expected json:预期的json:

var json = [
{
  "name": "parent 1",
  "level": "0",
  "children": [
    {
      "name": "child 1",
      "level": "1",
      "children": [
            {
            "name": "child 11",
            "level": "2"
            }
        ]
    },
    {
      "name": "child 2",
      "level": "1"
    }
  ]
}];

You could use Lodash to loop over your Objects and Array:你可以使用 Lodash 来循环你的对象和数组:

https://lodash.com/docs/4.17.15#forEach https://lodash.com/docs/4.17.15#forEach

I think by using Array.protoype.map() you can achieve the required goal.我认为通过使用Array.protoype.map()可以实现所需的目标。

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. map() 方法创建一个新数组,其中填充了对调用数组中的每个元素调用提供的函数的结果。

Please find a possible solution for your question:请为您的问题找到可能的解决方案:

 const data = [{"name": "parent 1","children": [{"name": "child 1","children": [{"name": "child 11"}]},{"name": "child 2"}]}]; const addLevel = (array, level) => { if (!level) { level = 0; } return array.map(e => { if (e.children) { e.children = addLevel(e.children, level + 1); } return { ...e, level }; }); }; const result = addLevel(data); console.log(result);

I hope that helps!我希望这有帮助!

for为了

var json = [{
  "name": "parent 1",
  "children": [
    {
      "name": "child 1",
      "children": [
            {
            "name": "child 11"
            }
        ]
    },
    {
      "name": "child 2"
    }
  ]
}];

A Simple Solution is一个简单的解决方案是

function mapping(ar , i = 0 ) {
    ar.map(el => {        
        el.level = i ;
        if(el.children){
            mapping(el.children , i+1);
        }
    });
}
mapping(json)



let solution = JSON.stringify(json) ;
console.log(solution)

[
{"name":"parent 1",
 "children":[{
              "name":"child 1",
              "children":[{
                           "name":"child 11",
                           "level":2,
                         }],
               "level":1
                },
               {
                "name":"child 2",
                "level":1
                }], 
 "level":0}
]

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

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