简体   繁体   中英

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.

For example:

The first level hierarchy should be level 0 and second level should be level 1, and so on.

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

Expected 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:

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

I think by using Array.protoype.map() you can achieve the required goal.

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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