gpt4 book ai didi

javascript - 如何从复杂对象数组中获取唯一属性数组

转载 作者:行者123 更新时间:2023-11-30 09:28:38 25 4
gpt4 key购买 nike

我有一个类似于

的对象数组
const array = [
{
documentId: "document1",
writers: [
{
name: "writer1",
date: "2017-12-11"
},
{
name: "writer2",
date: "2017-12-11"
}
]
},
{
documentId: "document2",
writers: [
{
name: "writer1",
date: "2017-12-11"
},
{
name: "writer3",
date: "2017-12-11"
}
]
},
{
documentId: "document3",
writers: [
{
name: "writer3",
date: "2017-12-11"
},
{
name: "writer4",
date: "2017-12-11"
}
]
},

我正在尝试提取所有唯一作者的姓名并将它们与他们编写的所有文档进行匹配,以便最终数组看起来像这样:

const finalArray = [
{name: "writter1", documents: ["document1", "document2"]},
{name: "writter2", documents: ["document1"]},
{name: "writter3", documents: ["document2", "document3"]},
{name: "writter4", documents: ["document3"]}
]

最佳答案

您可以使用 Map 将 writers 作为键,然后调用数组上的 reduce 将文档映射到 writer,然后调用 values()Map 对象上:

const ret = Array.from(array.reduce((acc, val) => {
val.writers.forEach(({ name }) => {
let w = acc.get(name) || { name: name, documents: [] };
w.documents = w.documents.concat(val.documentId);
acc.set(name, w);
});
return acc;
}, new Map()).values());

console.log(ret);

关于javascript - 如何从复杂对象数组中获取唯一属性数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47757712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com