Skip to content

Instantly share code, notes, and snippets.

@salmanx
Last active August 6, 2020 10:20
Show Gist options
  • Save salmanx/de69ce602f4d3b7748be8098801ef94f to your computer and use it in GitHub Desktop.
Save salmanx/de69ce602f4d3b7748be8098801ef94f to your computer and use it in GitHub Desktop.
var arr = [
{'id':1 ,'parentid' : 0},
{'id':2 ,'parentid' : 1},
{'id':3 ,'parentid' : 1},
{'id':4 ,'parentid' : 2},
{'id':5 ,'parentid' : 0},
{'id':6 ,'parentid' : 0},
{'id':7 ,'parentid' : 4}
];
unflatten = function( array, parent, tree ){
tree = typeof tree !== 'undefined' ? tree : [];
parent = typeof parent !== 'undefined' ? parent : { id: 0 };
var children = _.filter( array, function(child){ return child.parentid == parent.id; });
if( !_.isEmpty( children ) ){
if( parent.id == 0 ){
tree = children;
}else{
parent['children'] = children
}
_.each( children, function( child ){ unflatten( array, child ) } );
}
return tree;
}
tree = unflatten( arr );
console.log(tree)
const comments = [
{
id: 1,
parent_id: null
},
{
id: 2,
parent_id: 1
},
{
id: 3,
parent_id: 1
},
{
id: 4,
parent_id: 2
},
{
id: 5,
parent_id: 4
},
{
id: 6,
parent_id: null
},
{
id: 7,
parent_id: 6
}
];
const nest = (items, id = null, link = 'parent_id') =>
items
.filter((item) => item[link] === id)
.map((item) => ({...item, children: nest(items, item.id)}));
console.log(nest(comments));
var data = [
{
name: 'root',
id: 1,
parentLocation: null
},
{
name: 'a2',
parentLocation: {
id: 1
},
id: 2
},
{
name: 'a3',
parentLocation: {
id: 2
},
id: 3
},
{
name: 'a4',
parentLocation: {
id: 1
},
id: 4
},
{
name: 'a5',
parentLocation: {
id: 3
},
id: 5
}
];
const unflatten = (data) => {
var idToNodeMap = {};
var parentNode = [];
var root = null;
for (var i = 0; i < data.length; i++) {
var datum = data[i];
datum.children = [];
idToNodeMap[datum.id] = datum;
if (!datum.parentLocation) {
root = datum;
} else {
parentNode = idToNodeMap[datum.parentLocation.id];
parentNode.children.push(datum);
}
}
return root;
};
console.log(unflatten(data));
You can also use Map object, introduced in ES6.
let nodes = [
{ id: 1, pid: 0, name: "kpittu" },
{ id: 2, pid: 0, name: "news" },
{ id: 3, pid: 0, name: "menu" },
{ id: 4, pid: 3, name: "node" },
{ id: 5, pid: 4, name: "subnode" },
{ id: 6, pid: 1, name: "cace" }
];
function toTree(arr) {
let arrMap = new Map(arr.map((item) => [item.id, item]));
let tree = [];
for (let i = 0; i < arr.length; i++) {
let item = arr[i];
if (item.parentLocation) {
let parentItem = arrMap.get(item.parentLocation.id);
if (parentItem) {
let {children} = parentItem;
if (children) {
parentItem.children.push(item);
} else {
parentItem.children = [item];
}
}
} else {
tree.push(item);
}
}
return tree;
}
let tree = toTree(nodes);
console.log(tree);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment