如何从复杂对象数组中获取一组唯一属性(How to get an array of unique properties from an array of complex objects)

编程入门 行业动态 更新时间:2024-10-11 19:17:34
如何从复杂对象数组中获取一组唯一属性(How to get an array of unique properties from an array of complex objects)

我有一个类似的对象数组

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"]} ]

I have an array of objects similar to

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" } ] },

I'm trying to extract all the unique writer's names and match them to all the documents they have written so that the final array looks something like this:

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

最满意答案

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

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);

You can use Map to keep writers as keys then call reduce on your array to map documents to writers, then call values() on the Map object:

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);

更多推荐

本文发布于:2023-08-02 18:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1379782.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   属性   对象   array   objects

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!