簡體   English   中英

當對象中的三個屬性相等時,如何合並對象數組的對象? - JavaScript

[英]How can I merge the objects of an array of object when three attributes in the object are equal ? - JavaScript

當對象的三個屬性相同時,如何合並對象數組中的對象?

var data = [
 {
"Location": "London",
"OrderNo": "406643",
"Qty": "22.07",
"OrderDate": "28/11/2018",
"Status": null
 },
 {
"Location": "London",
"OrderNo": "526209",
"Qty": "21.00",
"OrderDate": "01/03/2019",
"Status": null
 },
 {
"Location": "London",
"OrderNo": "526209",
"Qty": "65.00",
"OrderDate": "01/03/2019",
"Status": null
 },
 {
"Location": "London",
"OrderNo": "526209",
"Qty": "61.00",
"OrderDate": "01/03/2019",
"Status": null
 },
 {
"Location": "London",
"OrderNo": "406643",
"Qty": "14.07",
"OrderDate": "28/11/2018",
"Status": null
 },
 {
"Location": "London",
"OrderNo": "406643",
"Qty": "12.07",
"OrderDate": "26/11/2018",
"Status": null
 },
];

我只想在對象的 Location、OrderNo 和 OrderDate 屬性相同時合並對象。 我還希望在其他三個屬性匹配時添加 qty 屬性。

這是我想要的輸出

var output = [
 {
"Location": "London",
"OrderNo": "406643",
"Qty": "36.14",
"OrderDate": "28/11/2018",
"Status": null
 },
 {
"Location": "London",
"OrderNo": "526209",
"Qty": "147.00",
"OrderDate": "01/03/2019",
"Status": null
 },
 {
"Location": "London",
"OrderNo": "406643",
"Qty": "12.07",
"OrderDate": "26/11/2018",
"Status": null
 },
];

請注意,在變量輸出中的第一個和第三個或最后一個對象中,兩個屬性相同但 orderDate 不同。

您可以組合使用reducefindIndex數組方法來獲得所需的內容。

對於reduce方法中的每次迭代,您使用findIndex檢查結果數組中是否已經存在與您的條件匹配的對象。 如果沒有匹配項,您只需將當前對象推送到結果數組中。 如果匹配,則對數量屬性求和。

 var data = [ { "Location": "London", "OrderNo": "406643", "Qty": "22.07", "OrderDate": "28/11/2018", "Status": null }, { "Location": "London", "OrderNo": "526209", "Qty": "21.00", "OrderDate": "01/03/2019", "Status": null }, { "Location": "London", "OrderNo": "526209", "Qty": "65.00", "OrderDate": "01/03/2019", "Status": null }, { "Location": "London", "OrderNo": "526209", "Qty": "61.00", "OrderDate": "01/03/2019", "Status": null }, { "Location": "London", "OrderNo": "406643", "Qty": "14.07", "OrderDate": "28/11/2018", "Status": null }, { "Location": "London", "OrderNo": "406643", "Qty": "12.07", "OrderDate": "26/11/2018", "Status": null } ]; data = data.reduce((acc, v) => { const index = acc.findIndex(o => { return o.Location === v.Location && o.OrderNo === v.OrderNo && o.OrderDate === v.OrderDate }); if (index >= 0) { acc[index].Qty = (Number(acc[index].Qty) + Number(v.Qty)).toFixed(2); } else { acc.push(v); } return acc; }, []); console.log(data);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM