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!
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; }
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; }
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; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.