Given the structure:
{
id: 'id-1',
name: 'name1',
ancestors: []
},{
id: 'id-2',
name: 'name2',
ancestors: []
},{
id: 'id-3',
name: 'name3',
ancestors: ['id-1']
},{
id: 'id-4',
name: 'name4',
ancestors: ['id-3', 'id-1']
}
Assume they are not sorted in any meaningful way.
The ancestors field is an array showing the path up to top level.
What would be the most efficient way to build nested lists (ul)?
My first thought is a recursive approach, but that seems troublesome as it would repeatedly search the entire list. Since this will be a javascript solution running in the browser that could be problematic.
You could build a tree and then render a nested list.
function getTree(data) {
var o = {};
data.forEach(function (a) {
var parent = a.ancestors[0];
if (o[a.id] && o[a.id].children) {
a.children = o[a.id].children;
}
o[a.id] = a;
o[parent] = o[parent] || {};
o[parent].children = o[parent].children || [];
o[parent].children.push(a);
});
return o.undefined.children;
}
function buildList(tree, target) {
var ul = document.createElement('ul');
tree.forEach(o => {
var li = document.createElement('li');
li.appendChild(document.createTextNode(o.name));
buildList(o.children || [], li);
ul.appendChild(li);
});
target.appendChild(ul);
}
var data = [{ id: 'id-1', name: 'name1', ancestors: [] }, { id: 'id-2', name: 'name2', ancestors: [] }, { id: 'id-3', name: 'name3', ancestors: ['id-1'] }, { id: 'id-4', name: 'name4', ancestors: ['id-3', 'id-1'] }],
tree = getTree(data);
console.log(tree);
buildList(tree, document.body);
Build up a Map for faster lookup:
const byId = new Map(array.map(el => ([el.id, el]));
Then its pretty simple to create a nested tree, we just check if a node has no ancestors, then its a root element, otherwise we add it as a children of the parent:
const root = [];
for(const obj of array) {
if(obj.ancestors.length) {
const parent = byId.get(obj.ancestors[0]);
if(parent.children) {
parent.children.push(obj);
} else {
parent.children = [obj];
}
} else {
root.push(obj);
}
}
So now root contains a nested tree, you can use a recursive approach to traverse it:
function traverse(elements) {
for(const el of elements) {
// Render ...
traverse(el.children || []);
}
}
traverse(root);
Related
I am trying to generate URLs for pages stored in a MongoDB in node.
Using the following function I want to traverse a javascript object that and display the path to each element.
I am nearly there, but I am stuck - There might even be a better way to do this using using Async (which I must admit, confuses me a bit).
Function: (demo)
function printTree(people, slug) {
for (var p = 0; p < people.length; p++) {
var root = people[p];
slug = slug + root.name + "/";
console.log(slug);
if (root.children.length > 0) {
var childrenCount = root.children.length;
for (var c = 0; c < childrenCount; c++) {
if (root.children[c].children.length > 0) {
printTree(root.children[c].children, slug + root.children[c].name + "/");
}
}
}
}
};
Output:
/michael/
/michael/angela/oscar
/michael/meredith/creed
/michael/meredith/creed/kelly
Expected Output:
/michael/
/michael/angela/
/michael/angela/oscar/
/michael/meredith/
/michael/meredith/creed/
/michael/meredith/kelly/
Object:
[
{
"name": "michael",
...
"children": [
{
"name": "angela",
...
"children": [
{
"name": "oscar",
...
"children": []
}
]
},
{
"name": "meredith",
...
"children": [
{
"name": "creed",
...
"children": []
},
{
"name": "kelly",
...
"children": []
}
]
},
{ ... }
]
}
]
If it helps, the data is stored using nested sets: https://github.com/groupdock/mongoose-nested-set
So there might be a better way to do the above work using nested sets (negating the above object).
Here you go. You don't need a second for loop, since your printTree function is going to loop through everything anyway (demo).
function printTree(people, slug){
slug = slug || '/';
for(var i = 0; i < people.length; i++) {
console.log(slug + people[i].name + '/');
if(people[i].children.length){
printTree(people[i].children, slug + people[i].name + '/')
}
}
}
You could also consider something in ECMA5 like this, in case you have further use of the tree or want to use some a seperator other than /. Nothing wrong with #bioball answer, this just gives you some more flexibility if wanted.
function makeTree(people, slug, sep) {
slug = slug || '/';
sep = sep || slug;
return people.reduce(function (tree, person) {
var slugPerson = slug + person.name + sep;
return tree.concat(slugPerson, makeTree(person.children, slugPerson, sep));
}, []);
}
function printTree(tree) {
tree.forEach(function (path) {
console.log(path);
});
}
printTree(makeTree(data));
On jsFiddle
Not a big fan of reinventing the wheel, so here is a solution using a object-scan. We use it for many data processing tasks and really like it because it makes things easier to maintain. However there is a learning curve. Anyways, here is how you could solve your question
// const objectScan = require('object-scan');
const scanTree = (tree) => objectScan(['**.children'], {
reverse: false,
breakFn: ({ isMatch, parents, context }) => {
if (!isMatch) {
return
}
context.push(
`/${parents
.filter((p) => 'name' in p)
.map(({ name }) => name)
.reverse()
.join('/')}/`
);
}
})(tree, []);
const tree = [{ id: '52fc69975ba8400021da5c7a', name: 'michael', children: [{ id: '52fc69975ba8400021da5c7d', parentId: '52fc69975ba8400021da5c7a', name: 'angela', children: [{ id: '52fc69975ba8400021da5c83', parentId: '52fc69975ba8400021da5c7d', name: 'oscar', children: [] }] }, { id: '52fc69975ba8400021da5c7b', parentId: '52fc69975ba8400021da5c7a', name: 'meredith', children: [{ id: '52fc69975ba8400021da5c7f', parentId: '52fc69975ba8400021da5c7b', name: 'creed', children: [] }, { id: '52fc69975ba8400021da5c7e', parentId: '52fc69975ba8400021da5c7b', name: 'kelly', children: [] }] }, { id: '52fc69975ba8400021da5c7c', parentId: '52fc69975ba8400021da5c7a', name: 'jim', children: [{ id: '52fc69975ba8400021da5c82', parentId: '52fc69975ba8400021da5c7c', name: 'dwight', children: [] }, { id: '52fc69975ba8400021da5c80', parentId: '52fc69975ba8400021da5c7c', name: 'phyllis', children: [] }, { id: '52fc69975ba8400021da5c81', parentId: '52fc69975ba8400021da5c7c', name: 'stanley', children: [] }] }] }];
scanTree(tree).map((e) => console.log(e));
// => /michael/
// => /michael/angela/
// => /michael/angela/oscar/
// => /michael/meredith/
// => /michael/meredith/creed/
// => /michael/meredith/kelly/
// => /michael/jim/
// => /michael/jim/dwight/
// => /michael/jim/phyllis/
// => /michael/jim/stanley/
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan
So I'm trying to write a recursive function that takes a flat array of objects with their value, id, and the id of their parent node and transform it to a tree structure, where the children of the structure are an array of nodes. Children need to be sorted by id and if its null it can be the root node.
The function im trying to write function toTree(data), only should take in the data array. I've been unable to do it without a parent. What I have so far is a function(below) that takes data and parent to get started.
input:
const tasks = [
{ id: 1, parent: null, value: 'Make breakfast' },
{ id: 2, parent: 1, value: 'Brew coffee' },
{ id: 3, parent: 2, value: 'Boil water' },
{ id: 4, parent: 2, value: 'Grind coffee beans' },
{ id: 5, parent: 2, value: 'Pour water over coffee grounds' }
];
output:
{
id: 1,
parent: null,
value: 'Make Breakfast',
children: [
{
id: 2,
parent: 1,
value: 'Brew coffee',
children: [
{ id: 3, parent: 2, value: 'Boil water' },
{ id: 4, parent: 2, value: 'Grind coffee beans' },
{ id: 5, parent: 2, value: 'Pour water over coffee grounds' }
]
}
]
}
funciton toTree(data) {
customtoTree (data, null);
}
function customToTree (data, parent) {
const out = [];
data.forEach((obj) => {
if (obj.parent === parent) {
const children = customToTree(data,obj.parent);
if (children.length) {
obj[children[0]] = children;
}
const {id,parent, ...content} = obj;
out.push(content);
}
});
return out;
}
I would really like to understand the correct logic on how to do this and think about this and how to do it without giving a parent explicitly.
I had the same question during an interview, and I haven't been able to solve it. I was also confused that the function should only take the array as a first and only argument.
But after reworking it later (and with some very good suggestions from a brilliant man), I realized that you can call the function with the array as the first and only argument the first time and then during the recursion call passing the parent as a second argument.
Inside the function, you only need to check if the second argument is undefined, if it is, you search in the array for your root object and assign it to your second argument.
So here is my solution, I hope it will be clearer :
function toTree(arr, item) {
if (!item) {
item = arr.find(item => item.parent === null)
}
let parent = {...item}
parent.children =
arr.filter(x => x.parent === item.id)
.sort((a, b) => a.id - b.id)
.map(y => toTree(arr, y))
return parent
}
toTree(tasks)
I couldn't check for more test cases but this is something I was quickly able to come up with which passes your use case, it looks not so good, I would recommend to use it as initial structure and then build on it. Also, I am assuming that tasks are sorted in ascending order by parent, i.e child will only appear after its parent in tasks array
const tasks = [
{ id: 1, parent: null, value: 'Make breakfast' },
{ id: 2, parent: 1, value: 'Brew coffee' },
{ id: 3, parent: 2, value: 'Boil water' },
{ id: 4, parent: 2, value: 'Grind coffee beans' },
{ id: 5, parent: 2, value: 'Pour water over coffee grounds' },
{ id: 6, parent: 5, value: 'Pour water over coffee grounds' },
{ id: 7, parent: 5, value: 'Pour water over coffee grounds' }
];
function Tree() {
this.root = null;
// this function makes node root, if root is empty, otherwise delegate it to recursive function
this.add = function(node) {
if(this.root == null)
this.root = new Node(node);
else
// lets start our processing by considering root as parent
this.addChild(node, this.root);
}
this.addChild = function(node, parent) {
// if the provided parent is actual parent, add the node to its children
if(parent.id == node.parent) {
parent.children[node.id] = new Node(node);
} else if(parent.children[node.parent]) {
// if the provided parent children contains actual parent call addChild with that node
this.addChild(node, parent.children[node.parent])
} else if(Object.keys(parent.children).length > 0) {
// iterate over children and call addChild with each child to search for parent
for(let p in parent.children) {
this.addChild(node, parent.children[p]);
}
} else {
console.log('parent was not found');
}
}
}
function Node (node) {
this.id = node.id;
this.parent = node.parent;
this.value = node.value;
this.children = {};
}
const tree = new Tree();
// We are assuming that tasks are sorted in ascending order by parent
for(let t of tasks) {
tree.add(t);
}
console.log(JSON.stringify(tree.root))
Let me know if you have questions. Lets crack it together
If your input is already sorted by id and no child node can come before its parent Node in the list, then you can do this in one loop and don't even need recursion:
const tasks = [
{ id: 1, parent: null, value: 'Make breakfast' },
{ id: 2, parent: 1, value: 'Brew coffee' },
{ id: 3, parent: 2, value: 'Boil water' },
{ id: 4, parent: 2, value: 'Grind coffee beans' },
{ id: 5, parent: 2, value: 'Pour water over coffee grounds' }
];
const tasksById = Object.create(null);
// abusing filter to do the work of a forEach()
// while also filtering the tasks down to a list with `parent: null`
const root = tasks.filter((value) => {
const { id, parent } = value;
tasksById[id] = value;
if(parent == null) return true;
(tasksById[parent].children || (tasksById[parent].children = [])).push(value);
});
console.log("rootNodes", root);
console.log("tasksById", tasksById);
.as-console-wrapper{top:0;max-height:100%!important}
Good day,
I need to convert strings as such:
Process1_Cat1_Cat2_Value1
Process1_Cat1_Cat2_Value2
Process2_Cat1_Cat2_Value1
into a nested array as such:
var d = [{
text: 'Process1',
children: [{
text: 'Cat1',
children: [{
text: 'Cat2',
children: [{
text: 'Value1'
},
{
text: 'Value2'
}]
}]
}]
},
{
text: 'Process2',
children: [{
text: 'Cat1',
children: [{
text: 'Cat2',
children: [{
text: 'Value1'
}]
}]
}]
},
];
The reason why I need to do this is to make use of a treeview to display my data:
https://www.npmjs.com/package/bootstrap-tree-view
I have looked at the following solution but was not able to get it working due to lowdash library throwing errors on the findWhere function:
Uncaught TypeError: _.findWhere is not a function
http://brandonclapp.com/arranging-an-array-of-flat-paths-into-a-json-tree-like-structure/
See below for the code:
function arrangeIntoTree(paths, cb) {
var tree = [];
// This example uses the underscore.js library.
_.each(paths, function(path) {
var pathParts = path.split('_');
pathParts.shift(); // Remove first blank element from the parts array.
var currentLevel = tree; // initialize currentLevel to root
_.each(pathParts, function(part) {
// check to see if the path already exists.
var existingPath = _.findWhere(currentLevel, {
name: part
});
if (existingPath) {
// The path to this item was already in the tree, so don't add it again.
// Set the current level to this path's children
currentLevel = existingPath.children;
} else {
var newPart = {
name: part,
children: [],
}
currentLevel.push(newPart);
currentLevel = newPart.children;
}
});
});
cb(tree);
}
arrangeIntoTree(paths, function(tree) {
console.log('tree: ', tree);
});
Any help will be appreciated!
You could use an iterative by looking for the text at the actual level. If not found create a new object. Return the children array for the next level until the most nested array. Then add the leaf object.
var data = ['Process1_Cat1_Cat2_Value1', 'Process1_Cat1_Cat2_Value2', 'Process2_Cat1_Cat2_Value1'],
result = data.reduce((r, s) => {
var keys = s.split('_'),
text = keys.pop();
keys
.reduce((q, text) => {
var temp = q.find(o => o.text === text);
if (!temp) {
q.push(temp = { text, children: [] });
}
return temp.children;
}, r)
.push({ text });
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have an app with a tree of nested nodes. all nodes are same type.
{
id: 1,
title: "node_1",
children: [
{
id: 2,
title: "node_2",
children: []
},
{
id: 3,
title: "node_3",
children: []
}
]
}
When user expanded some node (for example node with id === 3) i have to perform request to database and insert response (array children) inside of "children" property of node with id === 3 . So as result app state should be like this:
{
id: 1,
title: "node_1",
children: [
{
id: 2,
title: "node_2",
children: []
},
{
id: 3,
title: "node_3",
children: [
{
id: 4,
title: "node_4",
children: []
},
{
id: 5,
title: "node_5",
children: []
}
]
}
]
}
how can i paste array of children inside node_3 children property?
Given:
const layer1Id = 1;
const layer2Id = 3;
const newArray = [
{
id: 4,
title: "node_4",
children: [],
},
{
id: 5,
title: "node_5",
children: [],
}
];
Then, in the reducer you'll do:
return Object.assign({}, state, { children: state.children.map(child => {
if (child.id !== layer1Id) return child;
return Object.assign({}, child, { children: child.children.map(node => {
if (node.id !== layer2Id) return node;
return Object.assign({}, node, { children: node.children.concat(newArray) });
})});
})});
To make sure you don't mutate the previous state.
If it is dynamically or deeply nested, I'll recommend you to write some recursive function and use that instead.
Edit: here's sample recursive solution (untested). The indices are in order by level (ie: indices[0] refers to first level's id, indices[1] refers to second level's id):
const state = { ... };
const indices = [1, 3, 4, 5, 6];
const newArray = [ ... ];
const recursion = (node, ids, newChildren) => {
let children;
if (ids.length === 0) {
children = newChildren;
} else {
children = node.children.map(child => {
if (child.id !== ids[0]) return child;
return Object.assign({}, child, { children: recursion(child, ids.slice(1), newChildren) });
});
}
return Object.assign({}, node, { children });
};
recursion(state, indecies, newArray);
The suggested approach for relational or normalized data in a Redux store is to organize it in "normalized" fashion, similar to database tables. That will make it easier to manage updates. See http://redux.js.org/docs/FAQ.html#organizing-state-nested-data, How to handle tree-shaped entities in Redux reducers?, and https://github.com/reactjs/redux/pull/1269.
Just iterate through children array and push to correct one .
var id = expandedItemId;
for(var i = 0; i < obj.children.length; i++){
if(obj.id == expandedItemId){
obj.children.push(`data got from server`);
}
}
I am trying to generate URLs for pages stored in a MongoDB in node.
Using the following function I want to traverse a javascript object that and display the path to each element.
I am nearly there, but I am stuck - There might even be a better way to do this using using Async (which I must admit, confuses me a bit).
Function: (demo)
function printTree(people, slug) {
for (var p = 0; p < people.length; p++) {
var root = people[p];
slug = slug + root.name + "/";
console.log(slug);
if (root.children.length > 0) {
var childrenCount = root.children.length;
for (var c = 0; c < childrenCount; c++) {
if (root.children[c].children.length > 0) {
printTree(root.children[c].children, slug + root.children[c].name + "/");
}
}
}
}
};
Output:
/michael/
/michael/angela/oscar
/michael/meredith/creed
/michael/meredith/creed/kelly
Expected Output:
/michael/
/michael/angela/
/michael/angela/oscar/
/michael/meredith/
/michael/meredith/creed/
/michael/meredith/kelly/
Object:
[
{
"name": "michael",
...
"children": [
{
"name": "angela",
...
"children": [
{
"name": "oscar",
...
"children": []
}
]
},
{
"name": "meredith",
...
"children": [
{
"name": "creed",
...
"children": []
},
{
"name": "kelly",
...
"children": []
}
]
},
{ ... }
]
}
]
If it helps, the data is stored using nested sets: https://github.com/groupdock/mongoose-nested-set
So there might be a better way to do the above work using nested sets (negating the above object).
Here you go. You don't need a second for loop, since your printTree function is going to loop through everything anyway (demo).
function printTree(people, slug){
slug = slug || '/';
for(var i = 0; i < people.length; i++) {
console.log(slug + people[i].name + '/');
if(people[i].children.length){
printTree(people[i].children, slug + people[i].name + '/')
}
}
}
You could also consider something in ECMA5 like this, in case you have further use of the tree or want to use some a seperator other than /. Nothing wrong with #bioball answer, this just gives you some more flexibility if wanted.
function makeTree(people, slug, sep) {
slug = slug || '/';
sep = sep || slug;
return people.reduce(function (tree, person) {
var slugPerson = slug + person.name + sep;
return tree.concat(slugPerson, makeTree(person.children, slugPerson, sep));
}, []);
}
function printTree(tree) {
tree.forEach(function (path) {
console.log(path);
});
}
printTree(makeTree(data));
On jsFiddle
Not a big fan of reinventing the wheel, so here is a solution using a object-scan. We use it for many data processing tasks and really like it because it makes things easier to maintain. However there is a learning curve. Anyways, here is how you could solve your question
// const objectScan = require('object-scan');
const scanTree = (tree) => objectScan(['**.children'], {
reverse: false,
breakFn: ({ isMatch, parents, context }) => {
if (!isMatch) {
return
}
context.push(
`/${parents
.filter((p) => 'name' in p)
.map(({ name }) => name)
.reverse()
.join('/')}/`
);
}
})(tree, []);
const tree = [{ id: '52fc69975ba8400021da5c7a', name: 'michael', children: [{ id: '52fc69975ba8400021da5c7d', parentId: '52fc69975ba8400021da5c7a', name: 'angela', children: [{ id: '52fc69975ba8400021da5c83', parentId: '52fc69975ba8400021da5c7d', name: 'oscar', children: [] }] }, { id: '52fc69975ba8400021da5c7b', parentId: '52fc69975ba8400021da5c7a', name: 'meredith', children: [{ id: '52fc69975ba8400021da5c7f', parentId: '52fc69975ba8400021da5c7b', name: 'creed', children: [] }, { id: '52fc69975ba8400021da5c7e', parentId: '52fc69975ba8400021da5c7b', name: 'kelly', children: [] }] }, { id: '52fc69975ba8400021da5c7c', parentId: '52fc69975ba8400021da5c7a', name: 'jim', children: [{ id: '52fc69975ba8400021da5c82', parentId: '52fc69975ba8400021da5c7c', name: 'dwight', children: [] }, { id: '52fc69975ba8400021da5c80', parentId: '52fc69975ba8400021da5c7c', name: 'phyllis', children: [] }, { id: '52fc69975ba8400021da5c81', parentId: '52fc69975ba8400021da5c7c', name: 'stanley', children: [] }] }] }];
scanTree(tree).map((e) => console.log(e));
// => /michael/
// => /michael/angela/
// => /michael/angela/oscar/
// => /michael/meredith/
// => /michael/meredith/creed/
// => /michael/meredith/kelly/
// => /michael/jim/
// => /michael/jim/dwight/
// => /michael/jim/phyllis/
// => /michael/jim/stanley/
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan