gpt4 book ai didi

javascript - 基于 "category"属性和 sum "amount"属性减少对象数组

转载 作者:行者123 更新时间:2023-11-29 18:11:36 24 4
gpt4 key购买 nike

我有一个格式如下的 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] 

最佳答案

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));

http://jsbin.com/neqeli/2/

关于javascript - 基于 "category"属性和 sum "amount"属性减少对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26947972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com