Reputation: 180
Data
const data = [
{
"ID": 1,
"parent": "0",
"title": "Test-1"
},
{
"ID": 2,
"parent": "1",
"title": "Test-1-1"
},
{
"ID": 3,
"parent": "0",
"title": "Test-2"
},
{
"ID": 4,
"parent": "0",
"title": "Test-3"
},
{
"ID": 5,
"parent": "4",
"title": "Test-3-1"
},
{
"ID": 6,
"parent": "4",
"title": "Test-3-2"
},
];
Operations:
let parents = data.filter(item => item.parent == "0");
let parents_children = parents.map(item => item.children = data.filter(stop => stop.parent == item.ID));
console.log(parents_children);
isn't working at all.
console.log(parents);
is working perfectly. But I don't understand why... How is let parents_children
affecting let parents
? Is there a better solution for what I to to archive?
Upvotes: 1
Views: 66
Reputation: 8135
Assignment and return has to be different
let parents_children = parents.map(item => {
item.children = data.
filter(stop => stop.parent == item.ID);
return item;
});
// Better performance
let result = data2.reduce((map, cur) => {
if (cur.parent === "0") {
// parent
map[cur.ID] = map[cur.ID] || { children: [] };
map[cur.ID] = { ...map[cur.ID], ...cur };
} else {
if (!map[cur.parent]) map[cur.parent] = { children: [] };
map[cur.parent].children.push(cur);
}
return map;
}, {});
let finalResult = [];
for (const key in result) {
finalResult.push(result[key]);
}
console.log(JSON.stringify(finalResult, null, 4));
Working sample:
const data = [
{ ID: 1, parent: "0", title: "Test-1" },
{ ID: 2, parent: "1", title: "Test-1-1" },
{ ID: 3, parent: "0", title: "Test-2" },
{ ID: 4, parent: "0", title: "Test-3" },
{ ID: 5, parent: "4", title: "Test-3-1" },
{ ID: 6, parent: "4", title: "Test-3-2" }
];
let parents = data.filter(item => item.parent == "0");
let parents_children = parents.map(item => {
// create new object
return {
...item,
children : data.filter(stop => stop.parent == item.ID)
};
});
console.log(JSON.stringify(parents_children, null, 4));
console.log(data);
const data2 = [
{ ID: 1, parent: "0", title: "Test-1" },
{ ID: 2, parent: "1", title: "Test-1-1" },
{ ID: 3, parent: "0", title: "Test-2" },
{ ID: 4, parent: "0", title: "Test-3" },
{ ID: 5, parent: "4", title: "Test-3-1" },
{ ID: 6, parent: "4", title: "Test-3-2" }
];
// Better performance
let result = data2.reduce((map, cur) => {
if (cur.parent === "0") {
// parent
map[cur.ID] = map[cur.ID] || { children: [] };
map[cur.ID] = { ...map[cur.ID], ...cur };
} else {
if (!map[cur.parent]) map[cur.parent] = { children: [] };
map[cur.parent].children.push(cur);
}
return map;
}, {});
let finalResult = [];
for (const key in result) {
finalResult.push(result[key]);
}
console.log(JSON.stringify(finalResult, null, 4));
.as-console-row {color: blue!important}
Upvotes: 1
Reputation: 15166
You forgot to return from .map()
I believe.
Try the following:
let parents_children = parents.map(item => {
item.children = data.filter(stop => stop.parent == item.ID)
return item;
});
I hope this helps!
Upvotes: 2