Kamil Sobczyk
Kamil Sobczyk

Reputation: 387

How to count a depth level of nested objects?

I have an expample array of nested objects:

let arr = [{id: 0, children: []},
           {id: 1, children:[
             {id: 2, children: []},
             {id: 3, children: [
               {id: 4, children: []} 
             ]}
           ]}
         ];

I need to count depth level for each object. In all objects I have a parentId property too.

Result should be:

let arr = [{id: 0, depth: 0, children: []},
           {id: 1, depth: 0, children:[
             {id: 2, depth: 1, children: []},
             {id: 3, depth: 1, children: [
               {id: 4, depth: 2, children: []} 
             ]}
           ]}
         ];

I have an array of all the objects in a flat structure too.

Solutions?

Upvotes: 1

Views: 8747

Answers (4)

Ikram Ud Daula
Ikram Ud Daula

Reputation: 1321

You need to write a function that would be count for you. try this one.

function depth(o){
  var values;
  if (Array.isArray(o)) values = o;
  else if (typeof o === "object") values = Object.keys(o).map(k=>o[k]);
  return values ? Math.max.apply(0, values.map(depth))+1 : 1;
}

Upvotes: 1

Leroy Stav
Leroy Stav

Reputation: 718

function addDepth(arr, depth) {
  arr.map((entry) => {
    entry.depth = depth;
    addDepth(entry.children, depth+1);
  })
}

addDepth(arr, 0);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386680

You could iterate the arrays and add a depth.

const
    depth = d => o => {
        o.depth = d;
        (o.children || []).forEach(depth(d + 1));
    };

let tree = [{ id: 0, children: [] }, { id: 1, children: [{ id: 2, children: [] }, { id: 3, children: [{ id: 4, children: [] }] }] }];

tree.forEach(depth(0));

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Mark
Mark

Reputation: 92450

Just make a function that takes an array and a depth parameter that adds that depth to all objects in an array. Then call it on the children array with an incremented depth:

let arr = [{id: 0, children: []},{id: 1, children:[{id: 2, children: []},{id: 3, children: [{id: 4, children: []} ]}]}];

function addDepth(arr, depth = 0) {
  arr.forEach(obj => {
    obj.depth = depth
    addDepth(obj.children, depth + 1)
  })
}

addDepth(arr)
console.log(arr)

Upvotes: 8

Related Questions