简体   繁体   中英

Reduce an array of objects based on an object array property

I need help from some JavaScript/NodeJS experts. I'm using the v14 of NodeJS.

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

[
    {
        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:
{
    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. 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM