我有以下数组:
var curr = [{ “年份”:2019年, “ Title”:“资产管理示例”, “总和”:1020000.0, “预算”:0
}, {
"Year": 2019,
"Title": "Monday test 2",
"Sum": 2546658.0,
"Budget":100
}, {
"Year": 2020,
"Title": "Asset Management Sample",
"Sum": 1020000.0,
"Budget":1000
}, {
"Year": 2020,
"Title": "Monday test 2",
"Sum": 3472000.0,
"Budget":100
}, {
"Year": 2021,
"Title": "Asset Management Sample",
"Sum": 1020000.0,
"Budget":100
}, {
"Year": 2021,
"Title": "Monday test 2",
"Sum": 2452000.0,
"Budget":100
}]
我需要更改为:
[{
"Year": 2019,
"Asset Management Sample": 1020000.0,
"Monday test": 2546658.0
}, {
"Year": 2020,
"Asset Management Sample": 1020000.0,
"Monday test 2": 3472000.0
}, {
"Year": 2021,
"Asset Management Sample": 1020000.0,
"Monday test 2": 2452000.0
}]
在早期海报的帮助下,我使用了.reduce(从下方进行了稍微修改)来生成此图像:
var res = arr.reduce(function(acc, curr) {
acc[curr.Year] = acc[curr.Year];
acc[curr.Year] = acc[curr.Year] || { Year: curr.Year } ;
acc[curr.Year][curr.Title] = curr.Sum;
return acc;
我需要对此进行扩展,以包括每年所有预算值的总和(每年应该有一个预算值)。我在返回之前添加了以下行:
acc[curr.Year][curr.Budget] = curr[curr.Budget] || { Budget: curr.Budget } ;
它将为每个“预算”值添加单独的条目。如何在不影响其他返回数组的情况下将预算值求和并返回?
答案 0 :(得分:2)
像这样使用reduce
:
const arr = [{"Year":2019,"Title":"Asset Management Sample","Sum":1020000},{"Year":2019,"Title":"Monday test 2","Sum":2546658},{"Year":2020,"Title":"Asset Management Sample","Sum":1020000},{"Year":2020,"Title":"Monday test 2","Sum":3472000},{"Year":2021,"Title":"Asset Management Sample","Sum":1020000},{"Year":2021,"Title":"Monday test 2","Sum":2452000}];
const res = Object.values(arr.reduce((acc, { Year, Title, Sum }) => (acc[Year] = acc[Year] || { Year }, acc[Year][Title] = Sum, acc), {}));
console.log(res);
更多详细版本:
const arr = [{"Year":2019,"Title":"Asset Management Sample","Sum":1020000},{"Year":2019,"Title":"Monday test 2","Sum":2546658},{"Year":2020,"Title":"Asset Management Sample","Sum":1020000},{"Year":2020,"Title":"Monday test 2","Sum":3472000},{"Year":2021,"Title":"Asset Management Sample","Sum":1020000},{"Year":2021,"Title":"Monday test 2","Sum":2452000}];
const res = Object.values(arr.reduce((acc, { Year, Title, Sum }) => {
acc[Year] = acc[Year] || { Year };
acc[Year][Title] = Sum;
return acc;
}, {}));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
ES5语法:
var arr = [{"Year":2019,"Title":"Asset Management Sample","Sum":1020000},{"Year":2019,"Title":"Monday test 2","Sum":2546658},{"Year":2020,"Title":"Asset Management Sample","Sum":1020000},{"Year":2020,"Title":"Monday test 2","Sum":3472000},{"Year":2021,"Title":"Asset Management Sample","Sum":1020000},{"Year":2021,"Title":"Monday test 2","Sum":2452000}];
var res = arr.reduce(function(acc, curr) {
acc[curr.Year] = acc[curr.Year] || { Year: curr.Year };
acc[curr.Year][curr.Title] = curr.Sum;
return acc;
}, {});
res = Object.keys(res).map(function(key) {
return res[key];
});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }