我有一个类似于这个的json
{
"id": "1",
"month": "January",
"type": "inc",
"Value": "780.00",
"year": "2018",
},
{
"id": "2",
"month": "January",
"type": "inc",
"Value": "80.00",
"year": "2018",
},
{
"id": "3",
"month": "February",
"type": "inc",
"Value": "100.00",
"year": "2018",
},...
Run Code Online (Sandbox Code Playgroud)
现在我需要Value从对象中获取所有月份的所有内容,因为您可以看到我可能有更多具有相同月份名称的对象.我越接近创建2个数组1,其中包含Months和1的值,但是我被卡住,有人可以引导我走正确的道路吗?
期望的输出是获得这样的数组["January"=>1500, "February"=>2000...]或者有2个数组,1表示有收入的月份列表(我已经有它),第二个是这几个月的总收入,所以就像这样:["January", "February", "March"..]第二个一[1500, 2000, 300...]
您可以使用该函数逐月Array.prototype.reduce求和Value.
let arr = [{ "id": "1", "month": "January", "type": "inc", "Value": "780.00", "year": "2018", }, { "id": "2", "month": "January", "type": "inc", "Value": "80.00", "year": "2018", }, { "id": "3", "month": "February", "type": "inc", "Value": "100.00", "year": "2018", }],
result = arr.reduce((a, {month, Value}) => {
a[month] = (a[month] || 0) + +Value;
return a;
}, Object.create(null));
console.log(result);Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)