如何保留reduce
功能的累积值?每次迭代都会重置对象值。
const a = [1, 2, 3, 4, 5];
const b = {
1: {
name: 'Dan',
age: 25
},
2: {
name: 'Peter',
age: 28
},
3: {
name: 'Mark',
age: 38
},
4: {
name: 'Larry',
age: 32
},
5: {
name: 'Simon',
age: 25
},
}
const f = a.reduce((acc, val) => {
console.log({
acc
})
return {
[val]: {
age: b[val].age
}
}
}, {})
console.log(f); // 5: {age: 25}
我希望的结果是:
{
1: { age: 25 },
2: { age: 28 },
3: { age: 38 },
4: { age: 32 },
5: { age: 25 },
}
(此示例是演示)
答案 0 :(得分:5)
使用object spread(如此示例)或Object.assign()
将上一个累加器添加到返回的值中:
const a = [1, 2, 3, 4, 5];
const b = {"1":{"name":"Dan","age":25},"2":{"name":"Peter","age":28},"3":{"name":"Mark","age":38},"4":{"name":"Larry","age":32},"5":{"name":"Simon","age":25}};
const f = a.reduce((acc, val) => ({
...acc, // previous accumulator
[val]: {
age: b[val].age
}
}), {})
console.log(f); // 5: {age: 25}

答案 1 :(得分:0)
根据MDN
reduce()方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值。
在每次迭代中,您返回reduce()
函数内的新对象,并且您不存储该累加器的先前值。因此,您需要合并或为新值分配以前的值。
您可以使用
Object.assign()
方法获取所需结果的一种方法。
<强>样本强>
const a = [1, 2, 3, 4, 5];
const b = {1: {name: 'Dan',age: 25},2: {name: 'Peter',age: 28},3: {name: 'Mark',age: 38},4: {name: 'Larry',age: 32},5: {name: 'Simon',age: 25}}
let result = a.reduce((acc, val) => Object.assign(acc,{[val]: {age:b[val].age}}), {});
console.log(result);
&#13;
.as-console-wrapper {max-height: 100% !important;top: 0;}
&#13;
你可以这样做的第二种方式
obje[val]=newValue
并返回累加器。
<强>样本强>
const a = [1, 2, 3, 4, 5];
const b = {1: {name: 'Dan',age: 25},2: {name: 'Peter',age: 28},3: {name: 'Mark',age: 38},4: {name: 'Larry',age: 32},5: {name: 'Simon',age: 25}}
let result = a.reduce((acc, val) =>{
acc[val]= {age:b[val].age};
return acc;
}, {});
console.log(result);
&#13;
.as-console-wrapper {max-height: 100% !important;top: 0;}
&#13;
您可以使用
组合的另一种方式spread syntax
<强>样本强>
const a = [1, 2, 3, 4, 5];
const b = {1: {name: 'Dan',age: 25},2: {name: 'Peter',age: 28},3: {name: 'Mark',age: 38},4: {name: 'Larry',age: 32},5: {name: 'Simon',age: 25}}
let result = a.reduce((acc, val) => {
return {...acc,...{[val]:{age:b[val].age}}}
}, {});
console.log(result);
&#13;
.as-console-wrapper {max-height: 100% !important;top: 0;}
&#13;
答案 2 :(得分:0)
如果您的reduce函数中碰巧有一个if else语句,您的reduce累加器也可以重置,即您为if语句返回一个累加器但忘记处理else语句并且不返回累加器 - 在这种情况下触发 else 语句,不返回累加器,累加器变为未定义。
例如这有效:
let reducedArray = array.reduce((acc, curr) => {
if (
curr[
property_name
]
) {
return {
...acc,
...{
[curr.id]:
(acc[curr.id] ?? 0) +
curr[
property_name
]!
},
};
} else {
return acc;
}
}, {} as { [key: string]: number });
但这行不通:
let reducedArray = array.reduce((acc, curr) => {
if (
curr[
property_name
]
) {
return {
...acc,
...{
[curr.id]:
(acc[curr.id] ?? 0) +
curr[
property_name
]!
},
};
}
}, {} as { [key: string]: number });