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?
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?
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'});
You shouldn't need to use Object.assign()
, you can just add the key directly to your object:
var variable = "value";
myObject[variable] = variable;
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)