我使用以下减少:
const data = this.forms.reduce((accumulator, current) => {
return (accumulator[current.name] = current.value);
}
}, {});
this.forms
是:
[
{value: {document: "fsfsf", seria: "fsfsfsf"}, "name": "Form1"},
{value: {seria: "AA", age: "45"}, "name": "Form2"},
{value: {marry: "yes", hobby: "AAA"}, "name": "Form3"}
]
我需要构建这个结果:
{
"Form1": {document: "fsfsf", seria: "fsfsfsf"},
"Form2": {seria: "AA", age: "45"},
"Form3": {marry: "yes", hobby: "AAA"}
}
但是我得到了错误的结果:
{
{document: "fsfsf", seria: "fsfsfsf"},
"Form2": {}
}
我不明白为什么?
最佳答案
reduce
累加器的回调函数必须返回要应用于数组中后续元素的累加器。返回赋值表达式的结果返回表达式的结果(在本例中为 current.value
),而不是累加器。
const forms = [
{value: {document: "fsfsf", seria: "fsfsfsf"}, "name": "Form1"},
{value: {seria: "AA", age: "45"}, "name": "Form2"},
{value: {marry: "yes", hobby: "AAA"}, "name": "Form3"}
];
const data = forms.reduce((accumulator, current) => {
accumulator[current.name] = current.value;
return accumulator;
}, {});
console.log(data);
关于javascript - 减少 JS 中的对象错误行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58781825/