[英]javascript how to group and combine single array of object
我下面有一个 object 的数组,
[ { 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 } ]
我想将locationCode
分组并像这样将其他组合成一个 object
[ { locationCode: 'GMP', Qr: 46, Cash: 29 }, { locationCode: 'CMT', Qr: 35, Cash: 26, Voucher: 6 }, { locationCode: 'CMS', Qr: 22, Cash: 2 } ]
有人可以用 Javascript 或 lodash 解释一下吗,谢谢!
您可以使用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; }
您可以使用Array.reduce
创建一个由locationCode
键控的 object,我们还将使用 object destructuring
在每个键值处组装 object。
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; }
您可以将 object 分配给 object,按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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.