简体   繁体   English

减少 JS 错误行为中的 object?

[英]Reducing object in JS wrong behavior?

I use the following reduce:我使用以下减少:

const data = this.forms.reduce((accumulator, current) => {
       return (accumulator[current.name] = current.value);
      }
    }, {});

Where this.forms is: this.forms是:

[
{value: {document: "fsfsf", seria: "fsfsfsf"}, "name": "Form1"}, 
{value: {seria: "AA", age: "45"}, "name": "Form2"},
{value: {marry: "yes", hobby: "AAA"}, "name": "Form3"}
]

I need to build this result:我需要建立这个结果:

{
   "Form1":  {document: "fsfsf", seria: "fsfsfsf"},
   "Form2":  {seria: "AA", age: "45"},
   "Form3":  {marry: "yes", hobby: "AAA"}
}

But I get wrong result:但我得到错误的结果:

{
   {document: "fsfsf", seria: "fsfsfsf"},
   "Form2": {}
}

I can not get why?我不能得到为什么?

The callback function to the accumulator for reduce must return the accumulator to be applied to subsequent elements in the array.reduce到累加器的回调 function 必须返回累加器以应用于数组中的后续元素。 Returning the result of an assignment expression returns the result of the expression ( current.value in this case), not the accumulator.返回赋值表达式的结果返回表达式的结果(在本例中为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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM