我尝试使用Array.reduce
的组合,同时遍历数据以提供将数组中的值加在一起的结果,但前提是它们必须具有另一个匹配属性,并且我的数组示例是:
{"2018":[{"leaveYear":2018,"dayValue":60},{"leaveYear":2018,"dayValue":60}], "2019":[{"leaveYear":2019,"dayValue":60}]}
使用上面的示例,我想做的就是获取每个dayValue
的总和,但是仅当它们的leaveYear
匹配时才可以。所以我的结果是:
2018:120
2019:60
然后,将这些数据存储在我的数据库中,以leaveYear
作为键,并将简化的dayValue
作为值
我的进度
我首先创建新的数组,将这些数组对象按leaveYear
进行分组,因为它们可以是任何年份,也可以使用以下任意顺序:
function getSum(total, num) {
return total + num;
}
//used to total my values
function groupBy(array, property) {
var hash = {};
for (var i = 0; i < array.length; i++) {
if (!hash[array[i][property]]) hash[array[i][property]] = [];
hash[array[i][property]].push(array[i]);
}
return hash;
}
哪个会生成对象数组,每个对象的年份都匹配。然后,通过再次遍历,我开始减少:
var grouped = groupBy(multiSelectSaveArr,'leaveYear')
var multiDeductTotal = []
// my array of arrays by leaveYear
for(var i in grouped) {
var splitGroup = grouped[i]
console.log("SPLITGROUP:" + JSON.stringify(splitGroup))
//my log shows the result of
//SPLITGROUP:[{"leaveYear":2018,"dayValue":60},{"leaveYear":2018,"dayValue":60}]
//SPLITGROUP:[{"leaveYear":2019,"dayValue":60}]
//I then loop through splitGroup to reduce for my desired result by doing the following:
for(var ix in splitGroup) {
multiDeductTotal.push([splitGroup[ix].dayValue])
}
var deductReduce = 0 + multiDeductTotal.reduce(getSum)
//signal to database storing data
calendarPage.amendTakenAllowance(deductReduce, year)
}
我的问题是
这样做时,有时效果很好,但是当添加更多数组对象或几个leaveYears
时,循环有时似乎跳过或错过了数字,仅减少了给定{的值,或者没有{1}}
我如何遍历数组的每个leaveYear
,以减少信号并将其发送到数据库,然后再移至下一组值?
感谢您的帮助!
答案 0 :(得分:2)
您的输入是一个对象,其值是数组,您需要为原始对象中的每个键值对创建一个新对象。为此,您可以.map
将每个内部数组都放入一个条目中,并用dayValue
将数组中每个项目的.reduce
s相加,然后再转换为一个对象Object.fromEntries
:
const input = {
"2018": [{
"leaveYear": 2018,
"dayValue": 60
}, {
"leaveYear": 2018,
"dayValue": 60
}],
"2019": [{
"leaveYear": 2019,
"dayValue": 60
}]
};
const sumDays = yearArr => yearArr.reduce((a, b) => a + b.dayValue, 0);
const output = Object.fromEntries(
Object.values(input).map(yearArr => ([yearArr[0].leaveYear, sumDays(yearArr)]))
);
console.log(output);
如果您不能使用fromEntries
,则可以reduce
进入输出对象:
const input = {
"2018": [{
"leaveYear": 2018,
"dayValue": 60
}, {
"leaveYear": 2018,
"dayValue": 60
}],
"2019": [{
"leaveYear": 2019,
"dayValue": 60
}]
};
const sumDays = yearArr => yearArr.reduce((a, b) => a + b.dayValue, 0);
const output = Object.values(input).reduce((a, yearArr) => {
a[yearArr[0].leaveYear] = sumDays(yearArr);
return a;
}, {});
console.log(output);