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 = {};
// initialise 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'
},
{
catType: 'cat1',
name: 'name3'
},
{
catType: 'cat2',
name: 'name4'
},
{
catType: 'cat1',
name: 'name5'
}
]
// add each object to a list in above map based on the `catType` value
newList.forEach(detail => {
newMap[detail.catType].push(detail);
});
Expected outcome
{
cat1: [
{
catType: 'cat1',
name: 'name1'
},
{
catType: 'cat1',
name: 'name3'
},
{
catType: 'cat1',
name: 'name5'
}
],
cat2: [
{
catType: 'cat2',
name: 'name2'
},
{
catType: 'cat2',
name: 'name4'
}
],
}
To note:
I have looked at another prior question with some answers.
The answers in there is not what I am looking for.
This is to achieve a map where the keys are strings and values are array of objects.
And the data is obtained from 2 lists (newList and cats).
This is the past question for reference.
https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects