我在json之下,我想过滤模型,出售并按以下方式计算:
如果Model" xyz"已存在于json数组中,增加cnt,在这种情况下" xyz"在json下面三次来 - 所以我要添加cnt 5 + 4 + 2 = 11并且最终输出应该是{laptopModel: "xyz" , sold: "yes" , cnt: "11" }
- 我如何在jquery中执行此操作?
[
{
“laptopModel": “xyz",
“sold": yes,
“cnt": 5
},
{
“laptopModel": “xyz",
“sold": yes,
“cnt": 4
},
{
“laptopModel": “abc",
“sold": yes,
“cnt": 3
},
{
“laptopModel": “xyz",
“sold": yes,
“cnt": 2
}]
答案 0 :(得分:0)
尝试我的解决方案
var data = [
{
"laptopModel": "xyz",
"sold": "yes",
"cnt": 5
},
{
"laptopModel": "xyz",
"sold": "yes",
"cnt": 4
},
{
"laptopModel": "abc",
"sold": "yes",
"cnt": 3
},
{
"laptopModel": "xyz",
"sold": "yes",
"cnt": 2
}];
var temp = {};
for (var i = 0; i < data.length; i++) {
if (!temp[data[i]['laptopModel']]) {
temp[data[i]['laptopModel']] = data[i];
} else {
temp[data[i]['laptopModel']]['cnt'] += data[i]['cnt'];
}
}
var result = [];
for (var key in temp) {
if (temp.hasOwnProperty(key)) {
var obj = temp[key];
result.push(obj);
}
}
alert(JSON.stringify(result));
&#13;