Map Object Array and create new array from keys

Asked

Viewed 150 times

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' } ] }

1 answer

2


There is nothing wrong with your solution, it is simple and clear.

You may not use the map, once that method map one array in one another array. Thus, another option is to use the reduce. Something like that:

const originalArray = [
  { group: 'ONE', content: { a: 'b' } },
  { group: 'ONE', content: { b: 'c' } },
  { group: 'TWO', content: { c: 'd' } }
];

const newObject = originalArray.reduce((acc, current) => {
  const { group, content } = current;
  
  if (!acc[group]) {
    acc[group] = [content];
  } else {
    acc[group].push(content);
  }
  
  return acc;
}, {});

console.log(newObject);

There’s nothing wrong with a for, for..of, forEach or reduce, all will do the same thing. It will preferably personal. Just be careful that sometimes the reduce can be less familiar to beginners and make understanding the code more difficult.

  • 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.