我有一个像这个输入这样的对象数组,我想在另一个对象中嵌套一些对象(如果它们的 parentId 是父母的 forumId),
我的函数可以工作,但深度最大为 1,我怎样才能让它在 n 深度下工作?任何想法或优化表示赞赏!
编辑:指出后,输入不一定是有序的。
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;
}
这是预期的输出:
[
{
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,
},
],
},
],
},
]
这是当前的输出:
[
{
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,
},
],
},
]