[
{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:1,
title: 'test1',
nodes: [
{
id:2,
title: 'test2',
nodes: [
id: 3,
title: 'test3'
nodes: []
]
},
{
id:4,
title: 'test4',
nodes: []
}
],
{
id:5,
title: 'test5',
nodes: []
}
}
]
function createTree(data, levelKey, childrenKey) {
const tree = [];
const rootLevel = data.length && data[0][levelKey];
for (const n of data) {
let arr = tree;
for (let level = rootLevel; n[levelKey] > level++;) {
arr = arr[arr.length - 1][childrenKey];
}
arr.push(Object.assign({ [childrenKey]: [] }, n));
}
return tree;
}
const tree = createTree(arr, 'level', 'nodes');function createTree(
data,
{
levelKey = 'level',
childrenKey = 'children',
} = {}
) {
const rootLevel = data.length && data[0][levelKey];
return data.reduce((acc, {...n}) => (
acc[n[levelKey] + 1] = n[childrenKey] = [],
acc[n[levelKey]].push(n),
acc
), { [rootLevel]: [] })[rootLevel];
}
const tree = createTree(arr, { childrenKey: 'nodes' });