-1

I want to add a key-value pair to an object, but i want the key to be equal to a variable. Here's what I mean:

var variable;

Object.assign(myObject, {variable: value})

Is there any way to do this?

  • Possible duplicate of [Is it possible to add dynamically named properties to JavaScript object?](https://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object) – VLAZ Oct 06 '19 at 19:10
  • Possible duplicate of [Is this Javascript object literal key restriction strictly due to parsing?](https://stackoverflow.com/questions/2873163/is-this-javascript-object-literal-key-restriction-strictly-due-to-parsing) – Dexygen Oct 06 '19 at 19:10
  • @GeorgeJempty not relevant after ES6 introduced computed property names `{[computed]: somveValue}` – VLAZ Oct 06 '19 at 19:11
  • @VLAZ most certainly relevant. That question can still accept answers that reflect ES6. It happens all the time here on SO. – Dexygen Oct 06 '19 at 19:38

3 Answers3

3

Use Following code to use a variable as a key. Use [] operator to set the variable value to the key.

const key = "variableKey";

const object = {};

Object.assign(object, {[key]: 'value'});

thuva4
  • 1,185
  • 8
  • 13
0

You shouldn't need to use Object.assign(), you can just add the key directly to your object:

var variable = "value";

myObject[variable] = variable;
Kevin
  • 141
  • 7
0

According to MDN documentation:

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string.

Please note that all keys in the square bracket notation are converted to string unless they're Symbols, since JavaScript object property names (keys) can only be strings or Symbols

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Try your self into your browser console, the key will be named as "[object Object]", the same result of calling obj.toString():

let obj = {}
obj[new Object] = 'val'
console.log(obj)
Manu-sh
  • 114
  • 4