0

Is possible to deconstruct when using an anonymous function as a parameter.

For example (no real code):

With this common code:

// Common code.

const objectXX = {
    a: {x: "ax", y: "ay"},
    b: {x: "bx", y: "by"},
}

const printableXY = (x, y) => `(${x},${y})`

And this working code:

// Working code

const xyValues = Object.entries(objectXX).map(entry => {
    const [_, v] = entry
    return printableXY(v.x, v.y);
})

I want to refactor to use deconstructor in the map parameters and creating the anonymous function.

Is not possible to do something like these not working examples:


const xyValues = Object.entries(objectXX)
   .map(const [_, v] => printableXY(v.x, v.y));

const xyValues = Object.entries(objectXX)
   .map(const [_, [x, y]] => printableXY(x, y));

// Or even this one

const xyValues = Object.entries(objectXX)
   .map([_, [x, y]] => printableXY(x, y));
angelcervera
  • 3,699
  • 1
  • 40
  • 68
  • 1
    `Object.entries(objectXX).map(const [_, v] => printableXY(v.x, v.y));` -> `Object.entries(objectXX).map(([_, v]) => printableXY(v.x, v.y));` – VLAZ Jul 21 '20 at 06:29
  • I was reading that document, but I did not realize that parenthesis plus square brackets were necessary. Thanks – angelcervera Jul 21 '20 at 06:33
  • Yes, you always need round brackets, even if it's a single parameter, e.g., `f = ([x]) => x +1` or `g = ({y}) => y + 1` – VLAZ Jul 21 '20 at 06:35
  • So in my case, it would be something like this: `const Values = Object.entries(objectXX).map( ([_, {x,y}]) => printableXY(x, y));` – angelcervera Jul 21 '20 at 06:38
  • Indeed, that is correct since `Object.entries` gives you a key/value pair and in your case the values are objects. If you don't need the first parameter, you can also omit it directly and keep the comma: `Object.entries(objectXX).map( ([, {x,y}]) => printableXY(x, y));` this will only take the second item in the array and further do object destructuring on it, the first value will be skipped and not assigned to anything. But using a discard variable like `_` is also valid. Also a note - if you just need the values and not the keys, you can use `Object.values`. – VLAZ Jul 21 '20 at 06:41
  • Thanks. I need the key as well. I replaced it in the example to add the discarded case as well. – angelcervera Jul 21 '20 at 07:01
  • 1
    That's OK. I wasn't sure if the example was simplified or not, so I wanted to cover all the bases just in case :) – VLAZ Jul 21 '20 at 07:02

1 Answers1

0

Use the direct destructing syntax in your arrow function params:

const xyValues = Object.entries(objectXX)
   .map(([_, v]) => printableXY(v.x, v.y));
Charlie
  • 22,886
  • 11
  • 59
  • 90
  • Thanks, but @VLAZ pointed to duplicate response minutes ago. But yes, this is the way. – angelcervera Jul 21 '20 at 06:41
  • 1
    See the Array Destructuring section for a deeper look - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – Charlie Jul 21 '20 at 06:44