Javascript 基于“减少对象数组”;类别“;“财产和金额”;“金额”;财产
我有一个JSON对象,格式如下:Javascript 基于“减少对象数组”;类别“;“财产和金额”;“金额”;财产,javascript,arrays,object,Javascript,Arrays,Object,我有一个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"}] 我
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"}]
我想把它简化成这样:
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]