JavaScript ninjas! Now i have this collection:
var cats = [
{ id: 1, parent_id: 0, title: 'Movies' },
{ id: 2, parent_id: 0, title: 'Music' },
{ id: 3, parent_id: 1, title: 'Russian movies' },
{ id: 4, parent_id: 2, title: 'Russian music' },
{ id: 5, parent_id: 3, title: 'New' },
{ id: 6, parent_id: 3, title: 'Top10' },
{ id: 7, parent_id: 4, title: 'New' },
{ id: 8, parent_id: 4, title: 'Top10' },
{ id: 9, parent_id: 0, title: 'Soft' }
];
And i need this result:
var catsExtended = [
{ id: 1, parent_id: 0, childs: [ 3, 5, 6 ], title: 'Movies' },
{ id: 2, parent_id: 0, childs: [ 4, 7, 8 ], title: 'Music' },
{ id: 3, parent_id: 1, childs: [ 5, 6 ], title: 'Russian movies' },
{ id: 4, parent_id: 2, childs: [ 7, 8 ], title: 'Russian music' },
{ id: 5, parent_id: 3, childs: [], title: 'New' },
{ id: 6, parent_id: 3, childs: [], title: 'Top10' },
{ id: 7, parent_id: 4, childs: [], title: 'New' },
{ id: 8, parent_id: 4, childs: [], title: 'Top10' },
{ id: 9, parent_id: 0, childs: [], title: 'Soft' }
];
Help me pleace to collect all IDs
You could use a hash table for the reference to the already returned objects. And for the parents just iterate until parent_id becomes zero.
var cats = [{ id: 1, parent_id: 0, title: 'Movies' }, { id: 2, parent_id: 0, title: 'Music' }, { id: 3, parent_id: 1, title: 'Russian movies' }, { id: 4, parent_id: 2, title: 'Russian music' }, { id: 5, parent_id: 3, title: 'New' }, { id: 6, parent_id: 3, title: 'Top10' }, { id: 7, parent_id: 4, title: 'New' }, { id: 8, parent_id: 4, title: 'Top10' }, { id: 9, parent_id: 0, title: 'Soft' }],
catsExtended = cats.map(function (a) {
var id = a.parent_id;
this[a.id] = { id: a.id, parent_id: a.parent_id, children: [], title: a.title };
while (id) {
this[id].children.push(a.id);
id = this[id].parent_id;
}
return this[a.id];
}, Object.create(null));
console.log(catsExtended);
Combine map() and filter():
var catsExtended = cats.map(function(cat) {
return {
id: cat.id,
parent_id: cat.parent_id,
title: cat.title,
childs: cats.filter(function(c) {
return c.parent_id == cat.id;
}).map(function(c) {
return c.id
})
};
});
I think a simple Array.prototype.forEach can do a lot.
var cats = [{ id: 1, parent_id: 0, title: 'Movies' }, { id: 2, parent_id: 0, title: 'Music' }, { id: 3, parent_id: 1, title: 'Russian movies' }, { id: 4, parent_id: 2, title: 'Russian music' }, { id: 5, parent_id: 3, title: 'New' }, { id: 6, parent_id: 3, title: 'Top10' }, { id: 7, parent_id: 4, title: 'New' }, { id: 8, parent_id: 4, title: 'Top10' }, { id: 9, parent_id: 0, title: 'Soft' }];
cats.forEach(function(c) {
var pid = c.parent_id;
c.children = (this[c.id] = this[c.id] || []);
(this[pid] = (this[pid] || [])).push(c.id)
}, Object.create(null));
console.clear();
console.log(cats);
Related
I have this array of objects with nested objects "children".. the number of nested children arrays that can be is not defined
let a = [
{ id: 0, title: 'a', children: [ { id: 1, title: 'aa', children: [ { id: 2, title: 'aaa', children: []} ]}] },
{ id: 3, title: 'b', children: [ { id: 4, title: 'bb', children: []}] },
{ id: 5, title: 'c', children: [] },
{ id: 6, title: 'd', children: [ { id: 7, title: 'dd', children: [ { id: 8, title: 'ddd', children: []} ]}] },
]
and I need foreach them, take to the array.. with level of nested:
let b = [
{ id: 0, title: 'a', level: 0 },
{ id: 1, title: 'aa', level: 1 },
{ id: 2, title: 'aaa', level: 2 },
{ id: 3, title: 'b', level: 0 },
{ id: 4, title: 'bb', level: 1 },
{ id: 5, title: 'c', level: 0 },
{ id: 6, title: 'd', level: 0 },
{ id: 7, title: 'dd', level: 1 },
{ id: 8, title: 'ddd', level: 2 },
]
I tired recursively code, but its not working.. thank for help
Here is a recursive function called makeLevels that outputs your result.
let a = [
{ id: 0, title: 'a', children: [{ id: 1, title: 'aa', children: [{ id: 2, title: 'aaa', children: [] }] }] },
{ id: 3, title: 'b', children: [{ id: 4, title: 'bb', children: [] }] },
{ id: 5, title: 'c', children: [] },
{ id: 6, title: 'd', children: [{ id: 7, title: 'dd', children: [{ id: 8, title: 'ddd', children: [] }] }] },
];
function makeLevels(entry, result = [], level = 0) {
for (let i = 0, len = entry.length; i < len; i++) {
const item = entry[i];
result.push({ id: item.id, title: item.title, level });
if (item.children?.length) {
makeLevels(item.children, result, level + 1);
}
}
return result;
}
console.log(makeLevels(a));
Output:
[
{ "id": 0, "title": "a", "level": 0 },
{ "id": 1, "title": "aa", "level": 1 },
{ "id": 2, "title": "aaa", "level": 2 },
{ "id": 3, "title": "b", "level": 0 },
{ "id": 4, "title": "bb", "level": 1 },
{ "id": 5, "title": "c", "level": 0 },
{ "id": 6, "title": "d", "level": 0 },
{ "id": 7, "title": "dd", "level": 1 },
{ "id": 8, "title": "ddd", "level": 2 }
]
You can try this approach:
let a = [{ id: 0, title: 'a', children: [ { id: 1, title: 'aa', children: [ { id: 2, title: 'aaa', children: []} ]}] }, { id: 3, title: 'b', children: [ { id: 4, title: 'bb', children: []}] }, { id: 5, title: 'c', children: [] }, { id: 6, title: 'd', children: [ { id: 7, title: 'dd', children: [ { id: 8, title: 'ddd', children: []} ]}] },]
function flattenArray(arr, index = 0) {
return arr.reduce((acc, {children, ...rest}) => [
...acc,
{...rest, level: index},
...flattenArray(children, index+1)
],
[])
}
console.log(flattenArray(a))
To make it a little more readable, you could also do it like this.
let a = [{ id: 0, title: 'a', children: [ { id: 1, title: 'aa', children: [ { id: 2, title: 'aaa', children: []} ]}] }, { id: 3, title: 'b', children: [ { id: 4, title: 'bb', children: []}] }, { id: 5, title: 'c', children: [] }, { id: 6, title: 'd', children: [ { id: 7, title: 'dd', children: [ { id: 8, title: 'ddd', children: []} ]}] },]
function levels(obj, level = 0, arr = []) {
for (const { id, title, children } of obj) {
arr.push({ id, title, level });
if (Array.isArray(children)) levels(children, level + 1, arr);
}
return arr;
}
console.log(levels(a))
I have all my parent children in a single array data.What i want is to add a new attribute (level) on each objects.
Given i have data as
var data = [
{
id: 1,
parent_id: 0,
name: "Child1",
},
{
id: 4,
parent_id: 1,
name: "Child11",
},
{
id: 5,
parent_id: 4,
name: "Child111",
},
{
id: 11,
parent_id: 4,
name: "Child112"
},
{
id: 13,
parent_id: 11,
name: "Child1121",
},
{
id: 21,
parent_id: 11,
name: "Child1122"
},
{
id: 22,
parent_id: 11,
name: "Child1123"
},
{
id: 24,
parent_id: 1,
name: 'Child12'
}
]
I want a child-parent relationship based on the parent_id of the children and assign a new attribute in each object of the array as level which represents the depth level of the children based on its parent.My Expected result is :
var data = [
{
id: 1,
parent_id: 0, <-------represents root
name: "Child1",
level:0 <--------level based on its parent_id
},
{
id: 4,
parent_id: 1
name: "Child11",
level:1
},
{
id: 5,
parent_id: 4,
name: "Child111",
level:2
},
{
id: 11,
parent_id: 4,
name: "Child112",
level:2
},
{
id: 13,
parent_id: 11,
name: "Child1121",
level:3
},
{
id: 21,
parent_id: 11,
name: "Child1122",
level:3
},
{
id: 22,
parent_id: 11,
name: "Child1123",
level:3
},
{
id: 24,
parent_id: 1,
name: 'Child12',
level:1
}
]
My Code
function buildTree(elements, parent_id, level = 0) {
elements.forEach(element => {
if (element['parent_id'] == parent_id) {
console.log('parent_id', parent_id);
// elements.filter(item=>item!==element);
element['level'] = level;
}
else{
buildTree(elements,parent_id,level+1);
}
})
return elements;
}
For sorted data, you could take an object for the level count and map a new data set.
var data = [{ id: 1, parent_id: 0, name: "Child1" }, { id: 4, parent_id: 1, name: "Child11" }, { id: 5, parent_id: 4, name: "Child111" }, { id: 11, parent_id: 4, name: "Child112" }, { id: 13, parent_id: 11, name: "Child1121" }, { id: 21, parent_id: 11, name: "Child1122" }, { id: 22, parent_id: 11, name: "Child1123" }, { id: 24, parent_id: 1, name: 'Child12' }],
levels = {},
result = data.map(o => ({
...o,
level: levels[o.id] = o.parent_id in levels
? levels[o.parent_id] + 1
: 0
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try this
let parentLevel = []
data.map(parent => {
const { parent_id } = parent
if (!parentLevel.includes(parent_id)) {
parentLevel.push(parent_id);
}
})
const updatedData = data.map(parent => {
const { parent_id } = parent
parent.level = parentLevel.indexOf(parent_id)
return parent
})
console.log(updatedData);
The result is
(8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {id: 1, parent_id: 0, name: "Child1", level: 0}
1: {id: 4, parent_id: 1, name: "Child11", level: 1}
2: {id: 5, parent_id: 4, name: "Child111", level: 2}
3: {id: 11, parent_id: 4, name: "Child112", level: 2}
4: {id: 13, parent_id: 11, name: "Child1121", level: 3}
5: {id: 21, parent_id: 11, name: "Child1122", level: 3}
6: {id: 22, parent_id: 11, name: "Child1123", level: 3}
7: {id: 24, parent_id: 1, name: "Child12", level: 1}
If data is not sorted in a way that the parent is guaranteed to come before any of its children, then use a Map keyed by id values, which also gives better efficiency (no linear lookup in every iteration):
let data = [{ id: 1, parent_id: 0, name: "Child1" }, { id: 4, parent_id: 1, name: "Child11" }, { id: 5, parent_id: 4, name: "Child111" }, { id: 11, parent_id: 4, name: "Child112" }, { id: 13, parent_id: 11, name: "Child1121" }, { id: 21, parent_id: 11, name: "Child1122" }, { id: 22, parent_id: 11, name: "Child1123" }, { id: 24, parent_id: 1, name: 'Child12' }];
// optional step if you don't want to mutate the original objects in the array:
data = data.map(o => ({...o}));
const map = new Map(data.map(o => [o.id, o])).set(0, { level: -1 });
const setLevel = o => "level" in o ? o.level : (o.level = 1 + setLevel(map.get(o.parent_id)));
data.forEach(setLevel);
console.log(data);
You can omit the optional assignment when you are OK with adding the level property to the existing objects. But if you want the original data objects to remain untouched, and have newly created objects for storing the level property, then keep that line in.
I need to make something similar to treeview. It doesn't need collapsing it just needs to show some heirachy, but in a table view.
Flat data comes in from a database. I unflattened it and made a tree, but now that it's a tree, I wanted to turn it back into an array, so I can easily iterate using a for loop.
After looking at the source code of other treeviews my method was going to be like this:
From flat data from a db, unflatten:
[
{ id: 1, name: 'node1', parentId: 0 },
{ id: 2, name: 'node2', parentId: 1 },
{ id: 4, name: 'node4', parentId: 2 },
{ id: 5, name: 'node5', parentId: 2 },
{ id: 6, name: 'node6', parentId: 3 },
{ id: 3, name: 'node3', parentId: 1 },
]
The tree is now ordered and has a hierarchy (levels for indentation). Traverse the tree. I add level and children.
[
id: 1,
name: 'node1',
level: 0,
children: [
{
id: 2,
name: 'node2',
parentId: 1,
level: 1
children: [
{
id: 4,
name: 'node4',
parentId: 2,
level: 2,
children: []
},
{
id: 5,
name: 'node5',
parentId: 2,
children: []
},
]
},
{
id: 3,
name: 'node1',
parentId: 1,
children: [
{
id: 6,
name: 'node6',
parentId: 3,
children: []
},
]
},
]
]
Compress it back into an array form with order, level.
[
{ id: 1, name: 'node1', level: 0, parentId: 0, children: [...] },
{ id: 2, name: 'node2', level: 1, parentId: 1, children: [...] },
{ id: 4, name: 'node4', level: 2, parentId: 2, children: [...] },
{ id: 5, name: 'node5', level: 2, parentId: 2, children: [...] },
{ id: 3, name: 'node3', level: 1, parentId: 1, children: [...] },
{ id: 6, name: 'node6', level: 2, parentId: 3, children: [...] },
]
Of which I can easily create a table from.
I've gotten close with the following code:
var data = [
{ id: 1, name: 'node1', parentId: 0 },
{ id: 2, name: 'node2', parentId: 1 },
{ id: 4, name: 'node4', parentId: 2 },
{ id: 5, name: 'node5', parentId: 2 },
{ id: 6, name: 'node6', parentId: 3 },
{ id: 3, name: 'node3', parentId: 1 }
]
function unflatten (arr, parentId, level) {
let output = []
for (const obj of arr) {
if (obj.parentId === parentId) {
var children = unflatten(arr, obj.id, level+1)
obj.level = level
if (children.length) {
obj.children = children
}
output.push(obj)
}
}
// console.log(output)
return output
}
function flatten (tree) {
var output = []
for(const node of tree) {
if(node.children !== undefined){
var nodeChildren = flatten(node.children.reverse())
for(const child of nodeChildren){
output.push(child)
}
}
output.push(node)
}
return output
}
var dataCopy = Object.assign([], data)
console.log('data', dataCopy)
var res = unflatten(data, 0, 0)
console.log('tree', res)
var resCopy = Object.assign([], res)
var res2 = flatten(resCopy)
console.log('reflatten', res2)
Fiddle http://jsfiddle.net/ctd09r85/10/
That fiddle is the closest I've gotten, but it's a bit reversed and out of order.
How can I do this, and is this a reasonable way to build the tree view.
I have an array of objects that has information of nested data, and I want to convert the data to actual nested array data.
How can I convert this:
const data = [
{id: 1, parent_id: null, name: 'test1'},
{id: 2, parent_id: null, name: 'test2'},
{id: 3, parent_id: 2, name: 'test3'},
{id: 4, parent_id: 2, name: 'test4'},
{id: 5, parent_id: 4, name: 'test5'},
{id: 6, parent_id: 4, name: 'test5'},
{id: 7, parent_id: 2, name: 'test5'},
{id: 8, parent_id: 2, name: 'test5'},
{id: 9, parent_id: null, name: 'test5'},
{id: 10, parent_id: null, name: 'test5'},
]
to this:
const data = [
{id: 1, parent_id: null, name: 'test1'},
{
id: 2,
parent_id: null,
name: 'test2',
children: [
{id: 3, parent_id: 2, name: 'test3'},
{
id: 4,
parent_id: 2,
name: 'test4',
children: [
{id: 5, parent_id: 4, name: 'test5'},
{id: 6, parent_id: 4, name: 'test5'}
]
},
{id: 7, parent_id: 2, name: 'test5'},
{id: 8, parent_id: 2, name: 'test5'},
]
},
{id: 9, parent_id: null, name: 'test5'},
{id: 10, parent_id: null, name: 'test5'},
]
What is the best way to do this?
You could create recursive function with reduce method for this.
const data = [{id: 1, parent_id: null, name: 'test1'},{id: 2, parent_id: null, name: 'test2'},{id: 3, parent_id: 2, name: 'test3'},{id: 4, parent_id: 2, name: 'test4'},{id: 5, parent_id: 4, name: 'test5'},{id: 6, parent_id: 4, name: 'test5'},{id: 7, parent_id: 2, name: 'test5'},{id: 8, parent_id: 2, name: 'test5'},{id: 9, parent_id: null, name: 'test5'},{id: 10, parent_id: null, name: 'test5'},]
function nest(data, parentId = null) {
return data.reduce((r, e) => {
let obj = Object.assign({}, e)
if (parentId == e.parent_id) {
let children = nest(data, e.id)
if (children.length) obj.children = children
r.push(obj)
}
return r;
}, [])
}
console.log(nest(data))
You could take a single loop approach by using an object and the id and parent_id as key and collect the items/children to it.
The order is only important for the order in the children array.
const
data = [{ id: 1, parent_id: null, name: 'test1' }, { id: 2, parent_id: null, name: 'test2' }, { id: 3, parent_id: 2, name: 'test3' }, { id: 4, parent_id: 2, name: 'test4' }, { id: 5, parent_id: 4, name: 'test5' }, { id: 6, parent_id: 4, name: 'test5' }, { id: 7, parent_id: 2, name: 'test5' }, { id: 8, parent_id: 2, name: 'test5' }, { id: 9, parent_id: null, name: 'test5' }, { id: 10, parent_id: null, name: 'test5' }],
tree = function (data, root) {
var t = {};
data.forEach(o => {
Object.assign(t[o.id] = t[o.id] || {}, o);
t[o.parent_id] = t[o.parent_id] || {};
t[o.parent_id].children = t[o.parent_id].children || [];
t[o.parent_id].children.push(t[o.id]);
});
return t[root].children;
}(data, null);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
This is an interesting problem. One option if you want to keep linear time at the expense of some space it to make a lookup object based on id. Then you can loop through those values and push into either a parent object or the array:
const data = [{id: 1, parent_id: null, name: 'test1'},{id: 2, parent_id: null, name: 'test2'},{id: 3, parent_id: 2, name: 'test3'},{id: 4, parent_id: 2, name: 'test4'},{id: 5, parent_id: 4, name: 'test5'},{id: 6, parent_id: 4, name: 'test5'},{id: 7, parent_id: 2, name: 'test5'},{id: 8, parent_id: 2, name: 'test5'},{id: 9, parent_id: null, name: 'test5'},{id: 10, parent_id: null, name: 'test5'},]
let lookup = data.reduce((obj, item) => {
obj[item.id] = item
return obj
}, {})
let arr = Object.values(lookup).reduce((arr, val) =>{
if (val.parent_id == null) arr.push(val)
else (lookup[val.parent_id].children || ( lookup[val.parent_id].children = [])).push(val)
return arr
}, [])
console.log(JSON.stringify(arr, null, 2))
you could try this recursive approach
const data = [{id: 1, parent_id: null, name: 'test1'}, {id: 2, parent_id: null, name: 'test2'}, {id: 3, parent_id: 2, name: 'test3'}, {id: 4, parent_id: 2, name: 'test4'}, {id: 5, parent_id: 4, name: 'test5'}, {id: 6, parent_id: 4, name: 'test5'}, {id: 7, parent_id: 2, name: 'test5'}, {id: 8, parent_id: 2, name: 'test5'}, {id: 9, parent_id: null, name: 'test5'}, {id: 10, parent_id: null, name: 'test5'}];
const transform = arr => {
return arr.reduce((acc, elem) => {
const children = data.filter(el => el.parent_id === elem.id),
isPresent = findDeep(acc, elem);
if(!isPresent && children.length)
acc.push({...elem, children: transform(children)});
else if(!isPresent)
acc.push(elem);
return acc;
}, []);
}
const findDeep =(arr = [], elem) => (
arr.some(el => (el.id === elem.id) || findDeep(el.children, elem))
);
console.log(transform(data));
const data = [
{id: 1, parent_id: null, name: 'test1'},
{id: 2, parent_id: null, name: 'test2'},
{id: 3, parent_id: 2, name: 'test3'},
{id: 4, parent_id: 2, name: 'test4'},
{id: 5, parent_id: 4, name: 'test5'},
{id: 6, parent_id: 4, name: 'test5'},
{id: 7, parent_id: 2, name: 'test5'},
{id: 8, parent_id: 2, name: 'test5'},
{id: 9, parent_id: null, name: 'test5'},
{id: 10, parent_id: null, name: 'test5'},
]
const output = data.filter(
item => !item.parent_id
).map(
rootItem => ({
...rootItem,
children: data.filter(item => item.parent_id === rootItem.id),
})
)
console.log(output)
How could I flatten my array of object :
var mylist = [{
THEMEID: 1,
TITLE: "myTheme1",
PARENTID: 0,
children: [{
ITEMID: 1,
NAME: "myItem1",
THEMEID: 1,
PARENTID: 1,
TITLE: "myItem1"
},
{
THEMEID: 3,
TITLE: "mySubTheme1",
PARENTID: 1,
children: [{
ITEMID: 3,
NAME: "myItem3",
THEMEID: 3,
PARENTID: 2,
TITLE: "myItem3"
}]
}
]
},
{
THEMEID: 2,
TITLE: "myTheme2",
PARENTID: 0,
children: [{
ITEMID: 4,
NAME: "myItem4",
THEMEID: 2,
PARENTID: 1,
TITLE: "myItem4"
}]
},
{
THEMEID: 6,
TITLE: "myTheme3",
PARENTID: 0,
children: [{
THEMEID: 5,
TITLE: "mySubTheme3",
PARENTID: 1,
children: [{
THEMEID: 4,
TITLE: "mySubSubTheme3",
PARENTID: 2,
children: [{
ITEMID: 2,
NAME: "myItem2",
THEMEID: 4,
PARENTID: 3,
TITLE: "myItem2"
}]
}]
}]
}
];
console.log(mylist)
In a array where are indexes of children are to record in the children array of the parent array
How could I flatten my myList array to obtain a array as this, by having that the indexes of children to record in the children array of the parent:
Example :
var myFLaten = [
{THEMEID: 1, TITLE: "myTheme1", PARENTID: 0, children:[1,2]},
{ITEMID: 1, NAME: "myItem1", THEMEID: 1, PARENTID: 1, TITLE: "myItem1"},
{THEMEID: 3, TITLE: "mySubTheme1", PARENTID: 1, children:[3]},
{ITEMID: 3, NAME: "myItem3", THEMEID: 3, PARENTID: 2, TITLE: "myItem3"}]
console.log(myFLaten)
You could store the last children reference in a closure and iterate the given array. On inserting a new object in the flat array, another insert is made with the index of the inserted objects.
var tree = [{ THEMEID: 1, TITLE: "myTheme1", PARENTID: 0, children: [{ ITEMID: 1, NAME: "myItem1", THEMEID: 1, PARENTID: 1, TITLE: "myItem1" }, { THEMEID: 3, TITLE: "mySubTheme1", PARENTID: 1, children: [{ ITEMID: 3, NAME: "myItem3", THEMEID: 3, PARENTID: 2, TITLE: "myItem3" }] }] }, { THEMEID: 2, TITLE: "myTheme2", PARENTID: 0, children: [{ ITEMID: 4, NAME: "myItem4", THEMEID: 2, PARENTID: 1, TITLE: "myItem4" }] }, { THEMEID: 6, TITLE: "myTheme3", PARENTID: 0, children: [{ THEMEID: 5, TITLE: "mySubTheme3", PARENTID: 1, children: [{ THEMEID: 4, TITLE: "mySubSubTheme3", PARENTID: 2, children: [{ ITEMID: 2, NAME: "myItem2", THEMEID: 4, PARENTID: 3, TITLE: "myItem2" }] }] }] }],
flat = tree.reduce(function fn(parent, children) {
return function (r, o) {
var temp = { THEMEID: o.THEMEID, TITLE: o.TITLE, PARENTID: o.PARENTID, parentIndex: parent },
index = r.push(temp) - 1;
if ('ITEMID' in o) {
temp.ITEMID = o.ITEMID;
}
children.push(index);
if (o.children) {
o.children.reduce(fn(index, temp.children = []), r);
}
return r;
};
}(undefined, []), []);
console.log(flat);
.as-console-wrapper { max-height: 100% !important; top: 0; }