Skip to content

Instantly share code, notes, and snippets.

@SiddharthaChowdhury
Last active March 13, 2019 17:09
Show Gist options
  • Save SiddharthaChowdhury/8ea7e7b151223971505e9e89a2d60bef to your computer and use it in GitHub Desktop.
Save SiddharthaChowdhury/8ea7e7b151223971505e9e89a2d60bef to your computer and use it in GitHub Desktop.
Tree Hierarchy parent-child from array of objects
console.time("execution");
var posts = [{
"id": 1,
"name": "Earth",
"children": [2, 3]
}, {
"id": 2,
"name": "Asia",
"children": []
}, {
"id": 4,
"name": "Germany",
"children": [5]
}, {
"id": 3,
"name": "Europe",
"children": [4, 8]
},
{
"id": 5,
"name": "Hamburg",
"children": [7]
},
{
"id": 6,
"name": "Mars",
"children": []
},
{
"id": 7,
"name": "Stellingen",
"children": []
},
{
"id": 8,
"name": "Itali",
"children": [9]
},
{
"id": 9,
"name": "Rome",
"children": []
}
];
var tree = function (array) {
var r = {},
children = new Set,
result = [];
array.forEach(o => {
Object.assign(
r[o.id] = r[o.id] || {},
o,
{ children: o.children.map(id => (children.add(id), r[id] = r[id] || {})) }
);
});
return Object.values(r).filter(({ id }) => !children.has(id));
}(posts);
console.log(JSON.stringify(tree));
console.timeEnd("execution");
console.time("execution");
var posts = [{
"id": 1,
"name": "Earth",
"children": [2, 3]
}, {
"id": 2,
"name": "Asia",
"children": []
}, {
"id": 4,
"name": "Germany",
"children": [5]
}, {
"id": 3,
"name": "Europe",
"children": [4, 8]
},
{
"id": 5,
"name": "Hamburg",
"children": [7]
},
{
"id": 6,
"name": "Mars",
"children": []
},
{
"id": 7,
"name": "Stellingen",
"children": []
},
{
"id": 8,
"name": "Itali",
"children": [9]
},
{
"id": 9,
"name": "Rome",
"children": []
}
];
var discardables = [];
function getIndexOfById(id, posts) {
for(var i = 0; i < posts.length; i++){
if(posts[i].id == id) {
return i;
}
}
}
function discardUsedChilds (newPosts) {
for(var i in discardables) {
var index = getIndexOfById(discardables[i], newPosts)
newPosts.splice(index, 1);
}
}
function getElementById (id, posts) {
for(var i =0; i< posts.length; i++){
if(posts[i].id === id){
discardables.push(id);
return posts[i];
}
}
}
function refactorChildren(element, posts) {
if(!element.children || element.children.length === 0) {
return element;
}
var children = [];
for(var i = 0; i < element.children.length; i++){
var childElement = getElementById(element.children[i], posts);
children.push(childElement);
}
element.children = children;
return element;
}
function iterate(posts) {
var newPosts = [];
var des = [...posts]
for(var i = 0; i < des.length; i++){
var childedElement = refactorChildren(des[i], des);
newPosts.push(childedElement);
}
discardUsedChilds(newPosts)
return (newPosts);
}
var filtered = iterate(posts);
console.log(JSON.stringify(filtered))
console.timeEnd("execution");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment