0

I have been at this for over an hour and I am getting nowhere. I need to use a variable containing a string literal to replace a key in an Object for a DHX method, but it does not work.

When I place the 'actual' string into the method, it works perfectly. Here is what works ('col5' is the key in the object):

grid.data.update(2, {col5: 1} );

But ... if I now introduce a variable containing the same string literal, it fails (does not update the grid). This does not work:

let x = "col5"
grid.data.update(2, {x: 1} );

When I view this variable in console.log, it shows up perfectly. I even tried JSON.stringify to see if it needed to be converted, but that did not work either.

I'm looking for a way to use a variable in place of a key in this object.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ND_Coder
  • 127
  • 7
  • 2
    you want `{ [x]: 1 }` – Pointy Jul 23 '23 at 15:14
  • @Pointy lol, that was fast. I was writing an answer ;-; – Sally loves Lightning Jul 23 '23 at 15:16
  • Seriously? It was that easy? I tried so many things found on SO but not that. BRILLIANT! Thank you! Could I ask - as a newby - what do you officially call this approach so I know what to search for next time? – ND_Coder Jul 23 '23 at 15:16
  • 1
    @LightningMcQueen there's a duplicate or three out there somewhere. – Pointy Jul 23 '23 at 15:17
  • 2
    @ND_Coder it's usually called "computed property names". See for example [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names) – Robin Zigmond Jul 23 '23 at 15:20
  • @RobinZigmond. Just read your link. VERY helpful. Thank you. I think my biggest struggle with SO is not knowing what something is called to perform a quality search. I'm sure all the answers are out there if I just ask the right question!!! – ND_Coder Jul 23 '23 at 15:30
  • Hey @Pointy, could you make your comment into a full answer - since it appears to have solved OP's question? – Infinite_Maelstrom Jul 25 '23 at 01:44

0 Answers0