0

I have an array of object below,

[
  { locationCode: 'GMP', Qr: 46 },
  { locationCode: 'CMT', Qr: 35 },
  { locationCode: 'GMP', Cash: 29 },
  { locationCode: 'CMT', Cash: 26 },
  { locationCode: 'CMS', Qr: 22 },
  { locationCode: 'CMT', Voucher: 6 },
  { locationCode: 'CMS', Cash: 2 }
]

I want to group locationCode and combine others into one object like this

[
  { locationCode: 'GMP', Qr: 46, Cash: 29 },
  { locationCode: 'CMT', Qr: 35, Cash: 26, Voucher: 6 },
  { locationCode: 'CMS', Qr: 22, Cash: 2 }
]

Can someone explain that with Javascript or lodash, Thanks!

  • Does this answer your question? [Most efficient method to groupby on an array of objects](https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects) – Den Sep 29 '21 at 11:20

3 Answers3

0

You can easily achieve this result using Map

const arr = [
  { locationCode: "GMP", Qr: 46 },
  { locationCode: "CMT", Qr: 35 },
  { locationCode: "GMP", Cash: 29 },
  { locationCode: "CMT", Cash: 26 },
  { locationCode: "CMS", Qr: 22 },
  { locationCode: "CMT", Voucher: 6 },
  { locationCode: "CMS", Cash: 2 },
];

const map = new Map();
arr.forEach((o) =>
  map.set(o.locationCode, { ...(map.get(o.locationCode) ?? {}), ...o })
);

const result = [...map.values()];
console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */

.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}
DecPK
  • 24,537
  • 6
  • 26
  • 42
0

You can use Array.reduce to create an object keyed by locationCode, we'd also use object destructuring to assemble the object at each key value.

const input = [
  { locationCode: 'GMP', Qr: 46 },
  { locationCode: 'CMT', Qr: 35 },
  { locationCode: 'GMP', Cash: 29 },
  { locationCode: 'CMT', Cash: 26 },
  { locationCode: 'CMS', Qr: 22 },
  { locationCode: 'CMT', Voucher: 6 },
  { locationCode: 'CMS', Cash: 2 }
]

const result = Object.values(input.reduce((acc, cur) => { 
    acc[cur.locationCode] = acc[cur.locationCode] || { locationCode: cur.locationCode };
    acc[cur.locationCode] = { ...acc[cur.locationCode], ...cur };
    return acc;
}, {}))

console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
0

You could assign the object to an object, grouped by locationCode.

const
    data = [{ locationCode: 'GMP', Qr: 46 }, { locationCode: 'CMT', Qr: 35 }, { locationCode: 'GMP', Cash: 29 }, { locationCode: 'CMT', Cash: 26 }, { locationCode: 'CMS', Qr: 22 }, { locationCode: 'CMT', Voucher: 6 }, { locationCode: 'CMS', Cash: 2 }],
    result = Object.values(data.reduce((r, o) => {
        Object.assign(r[o.locationCode] ??= {}, o);
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392