繁体   English   中英

javascript 如何对 object 的单个数组进行分组和组合

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM