function createTree(arr, idKey, parentKey) {
const tree = {};
arr.forEach(n => tree[n[idKey]] = Object.assign({}, n));
return Object.values(tree).reduce((acc, n) => {
const parent = tree[n[parentKey]];
(parent ? parent.children = parent.children || {} : acc)[n[idKey]] = n;
return acc;
}, {});
}
const tree = createTree(data, 'id', 'parent_id');