Add a property to a JavaScript object using a variable as the name?

You can use this equivalent syntax:

obj[name] = value

Example:

let obj = {};
obj["the_key"] = "the_value";

or with ES6 features:

let key = "the_key";
let obj = {
  [key]: "the_value",
};

in both examples, console.log(obj) will return: { the_key: 'the_value' }

Leave a Comment