const createTree = (data, parentId = null) =>
data.reduce((acc, n) => (
n.parent_id === parentId && acc.push({
...n,
children: createTree(data, n.id),
}),
acc
), []);
const tree = createTree(data, 0);
или
function createTree(
data,
{
key = 'id',
parentKey = 'parentId',
childrenKey = 'children',
} = {}
) {
const tree = {};
data.forEach(n => tree[n[key]] = Object.assign({}, n));
return Object.values(tree).reduce((acc, n) => {
const p = tree[n[parentKey]];
(p ? p[childrenKey] = p[childrenKey] || {} : acc)[n[key]] = n;
return acc;
}, {});
}
const tree = createTree(data, { parentKey: 'parent_id' });