0

I have this array of objects and I want to regroup each object having the same guid on the same object For example for this array;

  [
      {"guid":"3a03a0a3-ddad-4607-9464-9d139d9989bf","comment":"text"},
      {"guid":"3a03a0a3-ddad-4607-9464-9d139d9989bf","scoreColor":"#fb8537","scoreLabel":"Coaching Later"},
      {"guid":"e400c6df-f6ca-420a-9f69-973d5d572dff","comment":"what"},
      {"guid":"0f608117-4285-4b88-872c-0dd22347b535","comment":"when"},
    ]

I want it like that :

  [
      {"guid":"3a03a0a3-ddad-4607-9464-9d139d9989bf","comment":"text", 
        "scoreColor":"#fb8537","scoreLabel":"Coaching Later"},

      {"guid":"e400c6df-f6ca-420a-9f69-973d5d572dff","comment":"what"},
      {"guid":"0f608117-4285-4b88-872c-0dd22347b535","comment":"when"},
    ]

I try this:

const groupBy = (key) => (array) =>
array.reduce((objectsByKeyValue, obj) => {
    const value = obj[key];
    objectsByKeyValue[value] = (objectsByKeyValue[value] || []).concat(obj);
    return objectsByKeyValue;
  }, {});
const grouped = groupBy('guid');
console.log('results', grouped(data.responses));

But it is not the same, that I want...

How can I make it ?

1 Answer 1

2

Here's a solution using object spread syntax and Array.prototype.reduce:

const ini = [{
    "guid": "3a03a0a3-ddad-4607-9464-9d139d9989bf",
    "comment": "text"
  },
  {
    "guid": "3a03a0a3-ddad-4607-9464-9d139d9989bf",
    "scoreColor": "#fb8537",
    "scoreLabel": "Coaching Later"
  },
  {
    "guid": "e400c6df-f6ca-420a-9f69-973d5d572dff",
    "comment": "what"
  },
  {
    "guid": "0f608117-4285-4b88-872c-0dd22347b535",
    "comment": "when"
  },
];

const groupBy = (array, key) => {
  return Object.values(array.reduce((acc, el) => {
    acc[el[key]] = { ...(acc[el[key]] || {}),
      ...el
    };
    return acc;
  }, {}));
};

console.log(groupBy(ini, 'guid'));

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.