在jQuery中有没有办法我可以添加包含SUM
的所有JSON对象的BC
作为客户端属性的值?我无法找到解决方案,我试过这个:
[
{
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"
}
]
答案 0 :(得分:1)
您可以按如下方式使用filter,map和reduce:
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);