Create a map based on 2 lists in a single operation

I have the following where I am adding objects into an array based on the catType value.

This works fine. But is there a way I could have written this more elegantly?

Possibly combining the steps plus without having to create empty arrays for the map at the start.

const cats = ['cat1', 'cat2']

let newMap = {};
// initialize map with values from above array as keys and values as empty arrays 
cats.forEach(category => {
    newMap[category.title] = [];
})

// list of objects
const newList = [
    {
        catType: 'cat1',
        name: 'name1'
    },
        {
        catType: 'cat2',
        name: 'name2'
    }
]

// add each object to a list in above map based on the catType value
newList.forEach(detail => {
    newMap[detail.catType].push(detail)
})

This would result in following map which is what I want.

{
    cat1: [
        {
            catType: 'cat1',
            name: 'name1'
        },
    ],
    cat2: [
        {
            catType: 'cat2',
            name: 'name2'
        },
    ],
}

17 thoughts on “Create a map based on 2 lists in a single operation”

Leave a Comment