簡體   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