gpt4 book ai didi

javascript - Ajax JSON SUMIF 数组包含特定单词

转载 作者:行者123 更新时间:2023-12-03 02:14:19 25 4
gpt4 key购买 nike

在 jQuery 中有没有一种方法可以添加包含 BC 的所有 JSON 对象的 SUM 作为客户端属性的值?我无法找到解决方案,我已经尝试过:

[
{
client: "BC",
users: "PHIL",
levels: "EAST",
SUM: "32,600.00"
},
{
client: "BC",
users: "PHIL",
levels: "EAST",
SUM: "12,600.00"
},
{
client: "AQ",
users: "PHIL",
levels: "WEST",
SUM: "20,600.00"
},
{
client: "AQ",
users: "PHIL",
levels: "WEST",
SUM: "16,600.00"
}
]

最佳答案

您可以按如下方式使用过滤器、映射和减少:

var items = [{"client": "BC", "users": "PHIL", "levels": "EAST", "SUM":"32,600.00"},
{"client": "BC", "users": "PHIL", "levels": "EAST", "SUM": "12,600.00"},
{"client": "AQ", "users": "PHIL", "levels": "WEST", "SUM": "20,600.00"},
{"client": "AQ", "users": "PHIL", "levels": "WEST", "SUM": "16,600.00"}];

var sum = items.filter(item => {
// get only ones with client property equals to 'BC'
return item.client === "BC";
}).map(item => {
// parse SUM property values removing the commas and convert them to int
return parseInt(item.SUM.replace(/,/g, ""));
}).reduce((a, b) => {
// sum
return a + b;
}, 0);

console.log(sum);

关于javascript - Ajax JSON SUMIF 数组包含特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49427140/

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