gpt4 book ai didi

javascript - 基于对象数组中不同单位的总和值

转载 作者:行者123 更新时间:2023-12-02 14:31:27 26 4
gpt4 key购买 nike

我陷入困境,我有 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com