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.
+ There are no comments
Add yours