我需要一些 JavaScript/NodeJS 专家的帮助。我正在使用 NodeJS 的 v14。
我想创建一个函数,将这种数组作为输入(假设它是一个团队列表):
[
{
name: 'IT',
tags: ['Department', 'Section', 'Organizational']
},
{
name: 'Male',
tags: ['Gender', 'Organizational']
},
{
name: 'Foo',
tags: []
}
]
...并作为输出返回按标签名称列出的团队,如下所示:
// Output:
{
Department: 'IT',
Section: 'IT',
Organizational: 'IT, Male',
Gender: 'Male'
}
对象键的顺序以及团队名称的顺序无关紧要。我可以用几行代码很容易地做到这一点,但我很确定使用我们的一些魔法 map()
、reduce()
函数和其他实用程序(如传播)很容易做到这一点。
有人可以帮助我以优化的方式实现这一目标吗?
谢谢!
答案 0 :(得分:0)
试试这个:
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)