当对象的三个属性相同时,如何将对象合并到对象数组中?
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不同。
答案 0 :(得分:0)
您可以结合使用reduce
和findIndex
数组方法来获得所需的内容。
对于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);