I have an array of objects like this input, and I want to nest some objects inside another objects (based if their parentId is the parents' forumId),
I got the function working but up to 1 depth, how can I get it working for n depth? Any idea or optimizations are appreciated!
EDIT: After pointing out, the input isn't necessarily ordered.
const input = [
{
forumId: 1,
parentId: null,
forumName: "Main",
forumDescription: "",
forumLocked: false,
forumDisplay: true,
},
{
forumId: 2,
parentId: 1,
forumName: "Announcements",
forumDescription: "Announcements & Projects posted here",
forumLocked: false,
forumDisplay: true,
},
{
forumId: 3,
parentId: 1,
forumName: "General",
forumDescription: "General forum, talk whatever you want here",
forumLocked: false,
forumDisplay: true,
},
{
forumId: 4,
parentId: 3,
forumName: "Introduction",
forumDescription: "A warming introduction for newcomers here",
forumLocked: false,
forumDisplay: true,
},
];
function processInput(forumInput) {
const topLevelForums = forumInput.filter(function (forum) {
return forum.parentId === null;
});
let output = topLevelForums;
forumInput.forEach(function (forum) {
if (forum.parentId !== null) {
const forumParentId = forum.parentId;
output.forEach(function (parentForum, idx) {
if (parentForum.forumId === forumParentId) {
if (!output[idx].hasOwnProperty("subForums")) {
output[idx].subForums = [];
}
parentForum.subForums.push(forum);
}
});
}
});
return output;
}
This is the expected output:
[
{
forumId: 1,
parentId: null,
forumName: "Main",
forumDescription: "",
forumLocked: false,
forumDisplay: true,
subForums: [
{
forumId: 2,
parentId: 1,
forumName: "Announcements",
forumDescription: "Announcements & Projects posted here",
forumLocked: false,
forumDisplay: true,
},
{
forumId: 3,
parentId: 1,
forumName: "General",
forumDescription: "General forum, talk whatever you want here",
forumLocked: false,
forumDisplay: true,
subForums: [
{
forumId: 4,
parentId: 3,
forumName: "Introduction",
forumDescription: "A warming introduction for newcomers here",
forumLocked: false,
forumDisplay: true,
},
],
},
],
},
]
This is the current output:
[
{
forumDescription: "",
forumDisplay: true,
forumId: 1,
forumLocked: false,
forumName: "Main",
parentId: null,
subForums: [
{
forumDescription: "Announcements & Projects posted here",
forumDisplay: true,
forumId: 2,
forumLocked: false,
forumName: "Announcements",
parentId: 1,
},
{
forumDescription: "General forum, talk whatever you want here",
forumDisplay: true,
forumId: 3,
forumLocked: false,
forumName: "General",
parentId: 1,
},
],
},
]
See Question&Answers more detail:
os