[英]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.