Destructuring In Lambda Function Returns Unexpected Value
Correct, expected value returned when function used with destructuring: [{'k':'key1','v':'val1'},{'k':'key2','v':'val2'},{'k':'key3','v':'val3'}] However, when lambda function is
Solution 1:
You could use destructuring inside of the parameters of the callback of Array#map
let array = [{ k: 'key1', v: 'val1', z: 'z1' }, { k: 'key2', v: 'val2', z: 'z2' }, { k: 'key3', v: 'val3', z: 'z3' }];
console.log(array.map(({ k, v }) => ({ k, v })));
.as-console-wrapper { max-height: 100%!important; top: 0; }
Solution 2:
This is caused beceause this code
{k, v} = x;
is not actually returning {k, v} but x. So you need to destruct object instead first of returning destructive assigment.
Solution 3:
The expression ({k, v} = x)
assigns to the globalk
and v
variables, and returns the right hand side value x
. So you've essentially got an identity function x => x
.
You should use destructuring in the parameters, and build an object literal as the return value:
[…].map( ({k, v}) => ({k, v}) );
Solution 4:
This works for me:
console.log(JSON.stringify([{
k: 'key1',
v: 'val1',
z: 'z1'
}, {
k: 'key2',
v: 'val2',
z: 'z2'
}, {
k: 'key3',
v: 'val3',
z: 'z3'
}].map(x => {
let { k, v } = x;
return { k, v };
})));
Post a Comment for "Destructuring In Lambda Function Returns Unexpected Value"