0

I want to merge Array of ObjectA containing ObjectB attribute by ObjectA attribute.

For example :

let myArray = [
  { name: 'Jeu', series: { name: 'testA', value: '89' } },
  { name: 'Dim', series: { name: 'testB', value: '490' } },
  { name: 'Dim', series: { name: 'testC', value: '978' } }
]

And I would like to transform it to

[
  { name: 'Jeu', series: { name: 'testA', value: '89' } },
  { name: 'Dim', series: [{ name: 'testB', value: '490' },{ name: 'testC', value: '978' } ] }
]

Am I able to do that with a simple reduce/map loop ?

1 Answer 1

1

You can first use reduce (with some spread syntax) to build an object that maps unique names and objects in the format you want to have, grouping series by name. Then, you can simply get the values from this object.

const myArray = [
  { name: 'Jeu', series: { name: 'testA', value: '89' } },
  { name: 'Dim', series: { name: 'testB', value: '490' } },
  { name: 'Dim', series: { name: 'testC', value: '978' } }
];

const map = myArray.reduce(
  (acc, curr) => ({
    ...acc,
    [curr.name]: {
      name: curr.name,
      series: acc[curr.name]
        ? [...acc[curr.name].series, curr.series]
        : [curr.series]
    }
  }),
  {}
);

const output = Object.values(map);
console.log(output);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.