简体   繁体   中英

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:

[
{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. Returning the result of an assignment expression returns the result of the expression ( current.value in this case), not the accumulator.

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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