[英]Reduce javascript array with nested children
我正在嘗試使用 mongodb 和 graphql 為網站創建一個幫助頁面。我為幫助頁面制作了這個架構 (joiGoose Schema):
constructor()
{
const joiSchema = joi.object
({
url: joi.string().required(),
title: joi.string().required(),
content: joi.string().required(),
children: joi.array().items
(
joi.string().meta({ _mongoose: { type: "ObjectId", ref: "Help" } }).optional(),
).meta({ _mongoose : { _id: false, timestamps: false } }),
published: joi.boolean().default(true).required(),
createdAt: joi.date().required().default(() => moment()),
updatedAt: joi.date().required().default(() => moment()),
});
const mongooseSchema = super(joigoose.convert(joiSchema));
return mongooseSchema;
}
我要做的第一件事是給出幫助部分的摘要。 我使用以下查詢從 mongodb 獲取所有頁面:
const allHelpPages = await MONGO.Help.find();`
它給了我一個包含所有幫助頁面的數組。 由於每個頁面可以有多個嵌套的子頁面(沒有最大級別),我需要的是減少所有頁面的子數組。
例子:
const allPages =
[
{
id: 1,
title: Test 1,
children:
[
2,
3
]
},
{
id: 2,
title: Test 2,
children:
[
4,
5
]
}
{
id: 3,
title: Test 3,
children:
[
6
]
}
{
id: 4,
title: Test 4
}
{
id: 5,
title: Test 5
}
{
id: 6,
title: Test 6,
children:
[
7
]
}
{
id: 7,
title: Test 7
}
]
應該結束於:
[
{
id: 1,
title: Test 1,
children:
[
{
id: 2,
title: Test 2,
children:
[
{
id: 4,
title: Test 4
},
{
id: 5,
title: Test 5
}
]
},
{
id: 3,
title: Test 3,
children:
[
{
id: 6,
title: Test 6,
children:
[
{
id: 7,
title: Test 7
}
]
}
]
}
]
},
]
您可以創建一個 object,您可以將其用作查找表,其中鍵是對象的 ID。 然后基於 object,您可以使用實際對象修改子對象 arrays,最后過濾掉其他 object 的子對象。
const data = [{"id":1,"title":"Test 1","children":[2,3]},{"id":2,"title":"Test 2","children":[4,5]},{"id":3,"title":"Test 3","children":[6]},{"id":4,"title":"Test 4"},{"id":5,"title":"Test 5"},{"id":6,"title":"Test 6","children":[7]},{"id":7,"title":"Test 7"}] const map = {}, isChild = {} for (let o of data) { map[o.id] = o } const result = Object.entries(map).map(([k, v]) => { const children = v.children; if (children) children.forEach((id, i) => { isChild[id] = true children[i] = map[id] }) return {...v, children} }).filter(({ id }) =>.isChild[id]) console.log(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.