Как посчитать уровень глубины вложенных объектов? - PullRequest
0 голосов
/ 04 января 2019

У меня есть массив примеров вложенных объектов:

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

Мне нужно посчитать уровень глубины для каждого объекта. Во всех объектах у меня тоже есть свойство parentId.

Результат должен быть:

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: []} 
             ]}
           ]}
         ];

У меня есть массив всех объектов в плоской структуре.

Решения

Ответы [ 4 ]

0 голосов
/ 04 января 2019

Вам нужно написать функцию, которая будет рассчитывать для вас. попробуйте это.

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;
}
0 голосов
/ 04 января 2019

Вы можете перебрать массивы и добавить глубину.

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; }
0 голосов
/ 04 января 2019
function addDepth(arr, depth) {
  arr.map((entry) => {
    entry.depth = depth;
    addDepth(entry.children, depth+1);
  })
}

addDepth(arr, 0);
0 голосов
/ 04 января 2019

Просто создайте функцию, которая принимает массив, и параметр depth, который добавляет эту глубину ко всем объектам в массиве. Затем вызовите его для массива children с увеличенной глубиной:

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