Javascript 对数组对象的所有值求和,如果查询编号相同,则合并对象
我有一个对象,里面是一个对象数组,我想合并具有相同Javascript 对数组对象的所有值求和,如果查询编号相同,则合并对象,javascript,arrays,typescript,ecmascript-6,javascript-objects,Javascript,Arrays,Typescript,Ecmascript 6,Javascript Objects,我有一个对象,里面是一个对象数组,我想合并具有相同InquiryNo的对象,在里面我想添加数量(首先将其转换为整数,然后添加),并将ProductDesc与,'连接起来。我尝试过这样做,但是我得到了错误的总和和一些错误的ProductDesc值。这就是我到目前为止所做的: for (var i = 0; i < obj.data.length; i++) { obj.data[i].Quantity = parseInt(obj.data[i].Quantity); } cons
InquiryNo
的对象,在里面我想添加数量
(首先将其转换为整数,然后添加),并将ProductDesc
与,'
连接起来。我尝试过这样做,但是我得到了错误的总和和一些错误的ProductDesc
值。这就是我到目前为止所做的:
for (var i = 0; i < obj.data.length; i++) {
obj.data[i].Quantity = parseInt(obj.data[i].Quantity);
}
console.log(typeof(obj.data[0].Quantity));
var data = obj.data, result = data.reduce(function (hash) {
return function (r, a) {
var key = a.InquiryNo;
if (!hash[key]) {
hash[key] = {
ColorCode: a.ColorCode,
CustCode: a.CustCode,
CustomerName: a.CustomerName,
InquireDate: a.InquireDate,
InquiryNo: a.InquiryNo,
LeadTime: a.LeadTime,
PatternCode: a.PatternCode,
Post: a.Post,
PostStatus: a.PostStatus,
ProductDesc: a.ProductDesc,
QualityCode: a.QualityCode,
Quantity: a.Quantity,
ShipDate: a.ShipDate,
StyleCode: a.StyleCode,
Unit: a.Unit
};
r.push(hash[key]);
console.log(hash[key]);
}
hash[key].Quantity += a.Quantity;
return r;
};
}(Object.create(null)), []);
console.log(result[0].Quantity);
如果我需要解释其他内容,请提前告诉我。我自己可能会使用for循环和一些lodash utils来完成此操作,但代码中的一个问题是,您总是添加
a.Quantity
,即使是新添加的键
。使用else
子句可以解决这个问题
..
console.log(hash[key]);
} else {
hash[key].Quantity += a.Quantity;
// code for ProductDesc
}
return r;
..
我就是这样做到的:
let result = [];
obj.data.forEach(function(obj) {
let id = obj.InquiryNo;
// converting quantity type from string to integer
obj.Quantity = parseInt(obj.Quantity);
if(!this[id]) {
result.push(this[id] = obj);
} else {
this[id].Quantity += parseInt(obj.Quantity);
this[id].InquireDate += `, ${obj.InquireDate}`;
this[id].ProductDesc += `, ${obj.ProductDesc}`;
}
}, Object.create(null));
console.log(result);
为什么
i
中的-1
?你想故意省略最后一个元素吗?@connexo不,我在b/w中检查了一些输入错误。。。谢谢你让我知道。我把问题又编辑了一遍
let result = [];
obj.data.forEach(function(obj) {
let id = obj.InquiryNo;
// converting quantity type from string to integer
obj.Quantity = parseInt(obj.Quantity);
if(!this[id]) {
result.push(this[id] = obj);
} else {
this[id].Quantity += parseInt(obj.Quantity);
this[id].InquireDate += `, ${obj.InquireDate}`;
this[id].ProductDesc += `, ${obj.ProductDesc}`;
}
}, Object.create(null));
console.log(result);