我有一个对象数组,如下所示:
const data = [ // array1 [{x: 1},{y:2},{z:3}],[{x: 1},{z:3}] ],[ // array2 [{x: 1},{z:3}] ]
需要完成的是将array1中的x与具有相同索引的array2中的x相加. y和z也是如此.最终结果应该是包含求和值的新对象数组.
像这样的东西:
[ [{totalXOne: 2},{totalYOne: 4},{totalZOne: 6}],[{totalXTwo: 2},{totalYTwo: 4},{totalZTwo: 6}],[{totalXThree: 2},{totalYthree: 4},{totalZThree: 6}],]
注意:所有数组的长度都相同,如果缺少值,则将替换为0)
我在MDN上找到了一些不错的东西,但是它总结了所有的x,y,z值,它返回了单个求和值,如下所示:
let initialValue = 0; let sum = [{x: 1},{x:2},{x:3}].reduce(function(accumulator,currentValue) { return accumulator + currentValue.x; },initialValue)
输出:
[ [{totalX: 3},{totalY: 6},{totalZ: 9}],// this is not what I need ]
有什么办法可以实现吗?
UPDATE
我从另一个来源收到JSON.它包含一个名为allEmpsData的属性映射,我得到了必要的salaryData和映射,我得到了NET | GROSS | TAX数据.
let allReports = []; setTimeout(() => { allEmpsData.map(x => { let reports = {}; let years = []; let months = []; let netArr = []; let grossArr = []; let mealArr = []; let taxArr = []; let handSalaryArr = []; x.salaryData.map(y => { years.push(y.year); months.push(y.month); netArr.push(y.totalNetSalary); grossArr.push(y.bankGrossSalary); mealArr.push(y.bankHotMeal); taxArr.push(y.bankContributes); handSalaryArr.push(y.handSalary); }) reports.year = years; reports.month = months; reports.net = netArr; reports.gross = grossArr; reports.meal = mealArr; reports.taxesData = taxArr; reports.handSalaryData = handSalaryArr; allReports.push(Object.assign([],reports)); }); },1000);
我可以说,一切都正常,但事实是,.我不知道更好.然后这里有魔力:
setTimeout(() => { result = allReports.reduce((r,a) => a.map((b,i) => b.map((o,j) => Object.assign(...Object .entries(o) .map(([k,v]) => ({ [k]: v + (getV(r,[i,j,k]) || 0) })) ) ) ),undefined ); console.log(result); },1500);
解决方法
您可以使用辅助函数来获取嵌套对象的值,并将值映射到同一索引.
const getV = (o,p) => p.reduce((t,k) => (t || {})[k],o); var data = [[[{ x: 1 },{ y: 2 },{ z: 3 }],[{ x: 1 },{ z: 3 }]],[[{ x: 1 },{ z: 3 }]]],result = data.reduce((r,a) => a.map((b,i) => b.map((o,j) => Object.assign(...Object .entries(o) .map(([k,k]) || 0) })) ) ) ),undefined ); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }