How to Create a New Key Object from a Variable in JavaScript?

Estimated read time 1 min read

In JavaScript, you can create a new object and set a key-value pair using either object literal notation or the Object constructor.

Here’s an example using object literal notation:

let keyName = "newKey";
let value = 42;

let obj = {};
obj[keyName] = value;

console.log(obj); // Output: {newKey: 42}

Here’s an example using the Object constructor:

let keyName = "newKey";
let value = 42;

let obj = new Object();
obj[keyName] = value;

console.log(obj); // Output: {newKey: 42}

In both cases, the value of the variable keyName is used as the key for the new property and the value of the variable value is used as the value for the new property.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply