gpt4 book ai didi

javascript - 减少 JS 中的对象错误行为?

转载 作者:行者123 更新时间:2023-11-30 13:48:34 27 4
gpt4 key购买 nike

我使用以下减少:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com