Home > Net >  How to combinine the content of multiple objects inside an array where there is the same key
How to combinine the content of multiple objects inside an array where there is the same key

Time:11-02

I want to combine the content of multiple objects inside an array that have the same key and join the content in one array.

I have the following array of object and I need to join in one array the content key value when I have AT_CALLCENTER or AT_SITE

[
  {
    candidateId: 'DEMO-000031',
    content: 'test',
    stage: 'AT_CALLCENTER'
  },
  {
    candidateId: 'DEMO-000031',
    content: 'test',
    stage: 'AT_CALLCENTER'
  },
  {
    candidateId: 'DEMO-000031',
    content: 'Hello Alex',
    stage: 'AT_CALLCENTER'
  },
  {
    candidateId: 'DEMO-000031',
    content: 'test',
    stage: 'AT_CALLCENTER'
  },
  {
    candidateId: 'DEMO-000031',
    content: 'ttests',
    stage: 'AT_SITE'
  },
  {
    candidateId: 'DEMO-000031',
    content: 'test',
    stage: 'AT_SITE'
  },
  {
    candidateId: 'DEMO-000031',
    content: 'testest',
    stage: 'AT_SITE'
  },
  {
    candidateId: 'DEMO-000031',
    content: 'test',
    stage: 'AT_SITE'
  }
]

Expected result

{
  "AT_CALLCENTER": ["test", "test", "Hello Alex", "test"],
  "AT_SITE": ["ttests", "...", "..."]
}

The result above shows that I need to have in one array all the content of the original object under the same key AT_CALLCENTER or AT_SITE

CodePudding user response:

You can use Array#reduce to do this:

data.reduce(
  (obj, { stage, content }) => (
    (stage in obj
      ? obj[stage].push(content) // if object property is already defined, push
      : (obj[stage] = [content]) // otherwise create a new property
    ),
    obj
  ),
  {} // start off with an empty object
);

const data = [{
    candidateId: 'DEMO-000031',
    content: 'test',
    stage: 'AT_CALLCENTER'
  },
  {
    candidateId: 'DEMO-000031',
    content: 'test',
    stage: 'AT_CALLCENTER'
  },
  {
    candidateId: 'DEMO-000031',
    content: 'Hello Alex',
    stage: 'AT_CALLCENTER'
  },
  {
    candidateId: 'DEMO-000031',
    content: 'test',
    stage: 'AT_CALLCENTER'
  },
  {
    candidateId: 'DEMO-000031',
    content: 'ttests',
    stage: 'AT_SITE'
  },
  {
    candidateId: 'DEMO-000031',
    content: 'test',
    stage: 'AT_SITE'
  },
  {
    candidateId: 'DEMO-000031',
    content: 'testest',
    stage: 'AT_SITE'
  },
  {
    candidateId: 'DEMO-000031',
    content: 'test',
    stage: 'AT_SITE'
  }
];

const result = data.reduce((obj, { stage, content }) => ((stage in obj ? obj[stage].push(content) : (obj[stage] = [content])), obj), {});
console.log(result);

CodePudding user response:

As in the previous answer, you could use a reduce function to accomplish what you want. The spread syntax can help it be done in a declarative manner, like so:

data.reduce((val,item) => (
    {...val, [`${item.stage}`]: [...(val[item.stage] || []), item.content]}
), {});
  • Related