1
I have an array called originalArray
, this array has two fields, group and content, group is a string and content any object.
Basically I want to divide this new object into an unknown number of fields, based on the number of different groups, the group will become the key field of our new object. The problem is that we always have to check if the key already exists (this is normal?).
I came to the following code to solve the problem, is there any better or easier solution, using map or something like?
const originalArray = [
{group: 'ONE', content: {'a': 'b'}},
{group: 'ONE', content: {'b': 'c'}},
{group: 'TWO', content: {'c': 'd'}},
];
const newArray = {};
originalArray.forEach(value => {
const { group, content } = value;
if (newArray[group] === undefined) newArray[group] = [content];
else {
newArray[group].push(content);
}
});
Entree:
[ {group: 'ONE', content: {'a': 'b'}}, {group: 'ONE', content: {'b': 'c'}}, {group: 'TWO', content: {'c': 'd'}}]
Expected exit:
{ ONE: [ { a: 'b' }, { b: 'c' } ], TWO: [ { c: 'd' } ] }
I’m leaving this link here: https://medium.com/@Jefflombardjr/understanding-foreach-map-filter-and-find-in-javascript-f91da93b9f2c with more map, reduce, filter and the like
– Pedro Caires