Reputation:
[['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?
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: ''
}
);
{ id: '', name: '' }
1111 // why this is not { id: '1111', name: '' } ???
{ id: '1111', name: 'aaaa' }
Upvotes: 3
Views: 54
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
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
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