0

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"
    }
  ]
}];
nito
  • 1,157
  • 8
  • 21
  • Please don't repost [poorly-received questions](https://stackoverflow.com/q/59809386/157247) without fixing the issues identified the last time you posted them. – T.J. Crowder Jan 19 '20 at 13:39
  • As I said before: Welcome to Stack Overflow! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Jan 19 '20 at 13:40
  • Also as I said before: That isn't a "json array." JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Jan 19 '20 at 13:40
  • And: [*For-each over an array in JavaScript?*](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript) seems at least relevant, but didn't want to dupehammer. – T.J. Crowder Jan 19 '20 at 13:41
  • I don't know why it is marked as poorly received question. When i post the question, the similarly answered questions are not related to this. –  Jan 19 '20 at 13:42
  • Read the above, and you'll know why. – T.J. Crowder Jan 19 '20 at 13:42

3 Answers3

0

You could use Lodash to loop over your Objects and Array:

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

nito
  • 1,157
  • 8
  • 21
0

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!

norbitrial
  • 14,716
  • 7
  • 32
  • 59
  • Thanks for the solution man! Can you tell me what does the below code does? I believe you are using spread operator. `return {...e,level}` –  Jan 19 '20 at 14:00
  • @sureshmg Yes, that's called spread syntax. Technically I'm copying the current element from each iteration and adding `level` to the returned value. Read further here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax – norbitrial Jan 19 '20 at 14:08
0

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}
]
Varun Bhalla
  • 415
  • 6
  • 8