Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}]

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?

like image 236
Chatter-Gotta-Chat Avatar asked Oct 29 '25 09:10

Chatter-Gotta-Chat


1 Answers

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; }
like image 159
Nina Scholz Avatar answered Oct 31 '25 12:10

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!