我試過下面的代碼。如何將JSON對象與相同的鍵並添加其他相應的值?
var SeatWithCat = [{
"level": "Level II",
"price": 5,
"quantity": 1,
"seats": "B3"
}, {
"level": "Level II",
"price": 5,
"quantity": 1,
"seats": "B1"
}, {
"level": "Level I",
"price": 10,
"quantity": 1,
"seats": "A2"
}, {
"level": "Level III",
"price": 30,
"quantity": 1,
"seats": "C1"
}, {
"level": "Level III",
"price": 30,
"quantity": 1,
"seats": "C2"
}, {
"level": "Level V",
"price": 50,
"quantity": 1,
"seats": "E1"
}, {
"level": "Level II",
"price": 5,
"quantity": 1,
"seats": "B2"
}, {
"level": "Level VI",
"price": 2,
"quantity": 1,
"seats": "F1"
}];
var temp = [];
var jsonarr = [];
for (var i = 0; i < SeatWithCat.length; i++) {
for (var j = 1; j < SeatWithCat.length; j++) {
if (SeatWithCat[i].level === SeatWithCat[j].level) {
temp.push({
level: SeatWithCat[i].level,
quantity: SeatWithCat[i].quantity + SeatWithCat[j].quantity,
price: SeatWithCat[i].price + SeatWithCat[j].price,
seats: SeatWithCat[i].seats + "," + SeatWithCat[j].seats
});
SeatWithCat = SeatWithCat.filter(function(el) {
return el.level !== SeatWithCat[i].level;
});
jsonarr = SeatWithCat;
alert(JSON.stringify(temp));
}
}
}
var finalObj = temp.concat(jsonarr);
alert(JSON.stringify(finalObj));
輸出:
[{
"level": "Level II",
"quantity": 2,
"price": 10,
"seats": "B3,B1"
}, {
"level": "Level III",
"quantity": 2,
"price": 60,
"seats": "C1,C1"
}, {
"level": "Level VI",
"quantity": 2,
"price": 4,
"seats": "F1,F1"
}, {
"level": "Level I",
"price": 10,
"quantity": 1,
"seats": "A2"
}, {
"level": "Level V",
"price": 50,
"quantity": 1,
"seats": "E1"
}]
它的正常工作具有同等水平的兩個對象,但如果與同級別的陣列中有兩個以上的物體其無法正常工作。我的要求是爲任何數量的具有相同級別的對象添加值。 在此先感謝!
可能重複[合併具有相同「鍵」的JSON對象並使用JavaScript添加它們的「值」](http://stackoverflow.com/questions/30833165/merge-json-object-with-same-key-並使用JavaScript添加他們的價值) – Mahi
爲了什麼是值得的,你有一個對象的數組;不是「JSON對象」。 JSON是一種可以解析*到*對象的文本格式。只要你實際使用它作爲數據,它不再是JSON。 –