1

Can the following javascript code written shorter? It creates a wrapper object with the id property as key and the element itself as value.

const f = elem => {
    return {[elem.id]: elem}
}

Sample:

f({id:'node/1', value:'tmp'})

Result:

{'node/1': {id:'node/1', value:'tmp'}}

I thought about arrow function style const f = elem => {[elem.id]: elem}, but Chrome didn't want it.

Nachtgold
  • 539
  • 1
  • 6
  • 27
  • 7
    `const f = elem => ({[elem.id]: elem})` - as per **[documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Returning_object_literals)** – Bravo Nov 04 '18 at 22:48
  • 1
    If you return an object from an arrow function you need more parentheses, to distinguish between the braces that denote a function body and the braces that denote an object: `elem => ({[elem.id]: elem})`. Duplicate of https://stackoverflow.com/q/28770415/3001761. – jonrsharpe Nov 04 '18 at 22:48
  • Possible duplicate of [ECMAScript6 arrow function that returns an object](https://stackoverflow.com/questions/28770415/ecmascript6-arrow-function-that-returns-an-object) – jonrsharpe Nov 05 '18 at 08:26
  • Thank you, I didn‘t see the link, because I thought the computed key is the problem. – Nachtgold Nov 05 '18 at 23:09

1 Answers1

-1

Bravo said it first, but:

const f = elem => ({[elem.id]: elem});

works perfectly

Kaspar Poland
  • 105
  • 1
  • 9