admin管理员组文章数量:1318570
Correct, expected value returned when function used with destructuring:
[{"k":"key1","v":"val1"},{"k":"key2","v":"val2"},{"k":"key3","v":"val3"}]
console.log(JSON.stringify([{
k: 'key1',
v: 'val1',
z: 'z1'
}, {
k: 'key2',
v: 'val2',
z: 'z2'
}, {
k: 'key3',
v: 'val3',
z: 'z3'
}].map(function(x) {
let {k, v} = x;
return {k, v };
})));
Correct, expected value returned when function used with destructuring:
[{"k":"key1","v":"val1"},{"k":"key2","v":"val2"},{"k":"key3","v":"val3"}]
console.log(JSON.stringify([{
k: 'key1',
v: 'val1',
z: 'z1'
}, {
k: 'key2',
v: 'val2',
z: 'z2'
}, {
k: 'key3',
v: 'val3',
z: 'z3'
}].map(function(x) {
let {k, v} = x;
return {k, v };
})));
However, when lambda function is used with destructuring, incorrect value returned:
[{"k":"key1","v":"val1","z":"z1"},{"k":"key2","v":"val2","z":"z2"},{"k":"key3","v":"val3","z":"z3"}]
console.log(JSON.stringify([{
k: 'key1',
v: 'val1',
z: 'z1'
}, {
k: 'key2',
v: 'val2',
z: 'z2'
}, {
k: 'key3',
v: 'val3',
z: 'z3'
}].map(x =>
({k, v} = x) )));
How would I use destructuring inside lambdas function such that it returns the same as using explicit function()
above?
4 Answers
Reset to default 5You 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; }
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.
The expression ({k, v} = x)
assigns to the global k
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}) );
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 };
})));
本文标签: javascriptdestructuring in lambda function returns unexpected valueStack Overflow
版权声明:本文标题:javascript - destructuring in lambda function returns unexpected value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742044825a2417720.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论