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

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

我希望迭代此 JSON 并添加一个键值对及其级别。

例如:

第一级层次结构应为 0 级,第二级应为 1 级,依此类推。

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

预期 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"
    }
  ]
}];

您可以使用 Lodash 来遍历您的对象和数组:

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

我认为使用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.

请为您的问题找到可能的解决方案:

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

希望对您有所帮助!

对于

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

一个简单的解决方案是

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}
]