我有一个格式如下的JSON对象:
balance = [{category:"clothing", amount:"120.50"}, {category:"groceries", amount:"145.23"}, {category:"clothing", amount:"97.34"}];
我想把它简化为这样的东西:
merged_totals = [{category:"clothing", amount:"217.84"}, {category:"groceries", amount:"145.23"}]
这是我正在使用的代码,它非常简单,但没有根据需要格式化对象并显示在上面:
combineCategories = function (data) {
var newData = [];
for (var prop in data) {
newData[ data[prop].category ] = 0; // set initial value otherwise it will be undefined
}
for (var prop in data) {
newData[ data[prop].category ] += +data[prop].amount;
}
console.log(newData);
}
返回:
// [Clothing: 195, Groceries: 140, Deposit: 995.6]
答案 0 :(得分:4)
var balance = [
{category: "clothing", amount:"120.50"},
{category: "groceries", amount:"145.23"},
{category: "clothing", amount:"97.34"}
];
var combineCategories = function (data) {
var res = {};
data.forEach(function (el) {
res[el.category] = (res[el.category])
? res[el.category] += +el.amount
: +el.amount;
});
return Object.keys(res).map(function (el) {
return {category: el, amount: res[el]};
});
}
console.log(combineCategories(balance));