[英]Reduce an array of objects based on an object array property
I need help from some JavaScript/NodeJS experts.我需要一些 JavaScript/NodeJS 专家的帮助。 I'm using the v14 of NodeJS.我正在使用 NodeJS 的 v14。
I would like to create a function that takes as an input this kind of array (let's say that it's a list of teams):我想创建一个 function 作为输入这种数组(假设它是一个团队列表):
[
{
name: 'IT',
tags: ['Department', 'Section', 'Organizational']
},
{
name: 'Male',
tags: ['Gender', 'Organizational']
},
{
name: 'Foo',
tags: []
}
]
... and returns as an output a list of teams by tag name like this: ...并以 output的形式返回按标签名称列出的团队列表,如下所示:
// Output:
{
Department: 'IT',
Section: 'IT',
Organizational: 'IT, Male',
Gender: 'Male'
}
The order of object keys as well as the order of the team names don't matter. object 键的顺序以及团队名称的顺序无关紧要。 I can do this quite easily with a few lines of code, but I'm quite sure that it would be easy to do using a few of our magic map()
, reduce()
functions and other utilities like spreading.我可以用几行代码很容易地做到这一点,但我很确定使用我们的一些魔法map()
、 reduce()
函数和其他实用程序(如传播)很容易做到这一点。
Anybody can help me achieve this in an optimized way?任何人都可以帮助我以优化的方式实现这一目标?
Thank you!谢谢!
Try this:尝试这个:
const organization = [ { name: 'IT', tags: ['Department', 'Section', 'Organizational'] }, { name: 'Male', tags: ['Gender', 'Organizational'] }, { name: 'Foo', tags: [] } ] const result = organization.reduce((acum, current) => { current.tags.forEach(tag => { if(acum[tag]) acum[tag] = `${acum[tag]}, ${current.name}` else acum[tag] = current.name }) return acum },{}) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.