D
D
dake12312017-09-27 14:12:38
JavaScript
dake1231, 2017-09-27 14:12:38

How to correctly collect a nested object without specifying a parent?

Hello! There is a tree in the form of an array with an indication of the nesting level, you need to make an array from it with nested objects.
The input is the following array:

[
{id:1, title: 'test1', level:0},
{id:2, title: 'test2', level:1},
{id3, title: 'test3', level:2},
{id:4, title: 'test4', level:1},
{id:5, title: 'test5', level:0},
]

the output should be like this:
[
{
   id:1,
   title: 'test1',
   nodes: [
      {
          id:2,
          title: 'test2',
         nodes: [
             id: 3,
             title: 'test3'
             nodes: []
        ]
      },
      {
          id:4,
          title: 'test4',
          nodes: []
      }
   ],
   {
       id:5,
       title: 'test5',
       nodes: []
   }
}
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2017-09-27
@dake1231

function getNested(data, idField, parentField, rootParent) {
  const
    root = [],
    obj = {};

  data.forEach(n => obj[n[idField]] = Object.assign({ nodes: [] }, n));

  Object.values(obj).forEach(n => {
    if (n[parentField] == rootParent) {
      root.push(n);
    } else {
      obj[n[parentField]].nodes.push(n);
    }
  });

  return root;
}

const nested = getNested([
  {id:1, title: 'test1', level:0},
  {id:2, title: 'test2', level:1},
  {id:3, title: 'test3', level:2},
  {id:4, title: 'test4', level:1},
  {id:5, title: 'test5', level:0},
], 'id', 'level', 0);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question