我陷入困境,我有 JSON 响应,例如
[{
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "2 acs",
"period": "all",
"in": "Morning"
}, {
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "1 acs",
"period": "all",
"in": "Evening"
}, {
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "2 cs",
"period": "all",
"in": "Morning"
}, {
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "1 cs",
"period": "all",
"in": "Evening"
}];
所以,我想获得具有数量+单位
的dose
键,但使用jQuery进行响应我想获得结果
例如- 3 个 Acs,3 个 cs。
最佳答案
您可以使用Array#forEach
迭代对象数组并创建对象来存储结果。
// An object to store the result
var result = {};
// Iterate over array of objects
arr.forEach(function(obj) {
// Extract quantity & unit
var quantity = parseInt(obj.dose.match(/\d+/)[0], 10),
unit = obj.dose.replace(/\d+/, '').trim();
// If the unit already exists in the result object
// Add the quantity to it
// else
// Store the quantity
result[unit] = result[unit] ? result[unit] + quantity : quantity;
});
var arr = [{
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "2 acs",
"period": "all",
"in": "Morning"
}, {
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "1 acs",
"period": "all",
"in": "Evening"
}, {
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "2 cs",
"period": "all",
"in": "Morning"
}, {
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "1 cs",
"period": "all",
"in": "Evening"
}];
var result = {};
arr.forEach(function(obj) {
var quantity = parseInt(obj.dose.match(/\d+/)[0], 10),
unit = obj.dose.replace(/\d+/, '').trim();
result[unit] = result[unit] ? result[unit] + quantity : quantity;
});
console.log(result);
上面的代码将以对象格式给出结果,如果您想要数组格式,只需添加
Object.keys(result).map(key => result[key] + ' ' + key)
在代码底部。
var arr = [{
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "2 acs",
"period": "all",
"in": "Morning"
}, {
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "1 acs",
"period": "all",
"in": "Evening"
}, {
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "2 cs",
"period": "all",
"in": "Morning"
}, {
"product": "CLINISod",
"potentiation": "BIOLOGICALLY ACTIVE",
"dose": "1 cs",
"period": "all",
"in": "Evening"
}];
var result = {};
arr.forEach(function(obj) {
var quantity = parseInt(obj.dose.match(/\d+/)[0], 10),
unit = obj.dose.replace(/\d+/, '').trim();
result[unit] = result[unit] ? result[unit] + quantity : quantity;
});
var arr = Object.keys(result).map(key => result[key] + ' ' + key);
console.log(arr);
关于javascript - 基于对象数组中不同单位的总和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37774696/