How To Combine Json Object With Same Key And Add Their Other Corresponding Values?
I tried the following code. var SeatWithCat = [{ 'level': 'Level II', 'price': 5, 'quantity': 1, 'seats': 'B3' }, { 'level': 'Level II', 'price': 5, 'quantity': 1,
Solution 1:
You can use Array.prototype.reduce()
to collect unique items in an dictionary, and then transform the dictionary back to array using Array.prototype.map()
:
functioncombine(arr) {
var combined = arr.reduce(function(result, item) {
var current = result[item.level];
result[item.level] = !current ? item : {
level: item.level,
price: current.price + item.price,
quantity: current.quantity + item.quantity,
seats: current.seats + ',' + item.seats
};
return result;
}, {});
returnObject.keys(combined).map(function(key) {
return combined[key];
});
}
varSeatWithCat = [{"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 result = combine(SeatWithCat);
console.log(result);
Solution 2:
You could use a hash table as reference to the same level object in the result set.
Iterate the array and check for hash - if not set generate a new object with the actual properties. Otherwise add quantity
and append seats
.
This proposal uses only one loop.
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" }],
result = [];
seatWithCat.forEach(function (o) {
if (!this[o.level]) {
this[o.level] = { level: o.level, price: o.price, quantity: o.quantity, seats: o.seats };
result.push(this[o.level]);
return;
}
this[o.level].quantity += o.quantity;
this[o.level].seats += ',' + o.seats;
}, Object.create(null));
console.log(result);
.as-console-wrapper { max-height: 100%!important; top: 0; }
Post a Comment for "How To Combine Json Object With Same Key And Add Their Other Corresponding Values?"