user5809117
user5809117

Reputation:

How come this reduce method doesn't give me object back?

[['id', '1111'], ['name', 'aaaaa']]

I have a list like this.

{ id: '1111', name: 'aaaa' }

And, I want to format the list to something like this.

So, I've tried to convert the list to the object in that format with reduce method of JavaScript like the below.

But, it doesn't work!

Could anyone tell me what I'm doing wrong and how to fix it, please?

Code

const result = [['id', '1111'], ['name', 'aaaaa']].reduce(
    (accumulator, list, index) => {
        const KEY = list[0];
        const VALUE = list[1];

        console.log(accumulator)

        if(KEY === 'id' || KEY === 'name') {
            return accumulator[KEY] = VALUE;
        }

        return accumulator

    },
    {
        id: '',
        name: ''
    }
);

log from the console.log(accumulator)

{ id: '', name: '' }
1111 // why this is not { id: '1111', name: '' } ???

Expected Result

{ id: '1111', name: 'aaaa' }

Upvotes: 3

Views: 54

Answers (3)

polunzh
polunzh

Reputation: 318

You should return accumulator in reduce callback, but the result of accumulator[KEY] = VALUE statement is not accmulator, so remove return key word in the if clause:

if(KEY === 'id' || KEY === 'name') {
    accumulator[KEY] = VALUE;
}

Upvotes: 2

charlietfl
charlietfl

Reputation: 171679

Only return once. In the conditional only set the property

if(KEY === 'id' || KEY === 'name') {
   /*return*/ accumulator[KEY] = VALUE;
   // ^^ remove the return
}

You aren't returning the full object otherwise

Upvotes: 1

Rafael
Rafael

Reputation: 7746

This code is returning the value...remove the return statement.

    if(KEY === 'id' || KEY === 'name') {
        return accumulator[KEY] = VALUE;
    }

To

    if(KEY === 'id' || KEY === 'name') {
         accumulator[KEY] = VALUE;
    }

Upvotes: 1

Related Questions