Home > front end >  How can i merge an array of objects with with a unique key?
How can i merge an array of objects with with a unique key?

Time:12-29

i have the following array of objects.i want to merge these objects with month as a unique id.

[
  { month: 7, openSlot: 9, confirmed: 0, requested: 0, total: 0 },
  { month: 5, openSlot: 0, confirmed: 6, requested: 0, total: 0 },
  { month: 7, openSlot: 0, confirmed: 0, requested: 0, total: 17 }
]

The above array should be merged like this


  { month: 7, openSlot: 9, confirmed: 0, requested: 0, total: 17 },
 { month: 5, openSlot: 0, confirmed: 6, requested: 0, total: 0 }

CodePudding user response:

You could separate month from the object and add all other values by their key.

const
    data = [{ month: 7, openSlot: 9, confirmed: 0, requested: 0, total: 0 }, { month: 5, openSlot: 0, confirmed: 6, requested: 0, total: 0 }, { month: 7, openSlot: 0, confirmed: 0, requested: 0, total: 17 }],
    result = Object.values(data.reduce((r, { month, ...o }) => {
        r[month] ??= { month };
        Object
            .entries(o)
            .forEach(([k, v]) => r[month][k] = (r[month][k] || 0)   v);
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

You could do this using forEach and adding the values of each key. NB: if you are interested in a more optimized code, use the solution by @Nina Scholz

const data = [
  { month: 7, openSlot: 9, confirmed: 0, requested: 0, total: 0 },
  { month: 5, openSlot: 0, confirmed: 6, requested: 0, total: 0 },
  { month: 7, openSlot: 0, confirmed: 0, requested: 0, total: 17 }
]

function merge(data) {

  let tempObj = {};

  data.forEach(item => {

    if (tempObj[item['month']]) {
      let temp = {}
      Object.entries(item).forEach(([key, value]) => {

        temp[key] = key === 'month' ? value : value   tempObj[item['month']][key];

      })
      tempObj[item['month']] = temp

    } else {
      tempObj[item['month']] = item
    }

  });

  return tempObj;
}

console.log(Object.values(merge(data)));

  • Related