javascript variable as object key

Javascript Variable as Object Key

Have you ever needed to use a dynamic value as an object key in Javascript? This can be a bit tricky, but there are a few ways to accomplish it.

Method 1: Bracket Notation


let key = "dynamicKey";
let obj = {
  [key]: "value"
};
console.log(obj.dynamicKey); // Output: "value"

The bracket notation allows you to use a variable as a key in an object. By wrapping the variable name in brackets, you can use its value as the key. In the example above, the variable 'key' is assigned to the string 'dynamicKey'. When the object is created, the bracket notation is used to assign the value 'value' to the dynamic key 'dynamicKey'.

Method 2: Object.defineProperty()


let key = "dynamicKey";
let obj = {};
Object.defineProperty(obj, key, {
  value: "value"
});
console.log(obj.dynamicKey); // Output: "value"

The Object.defineProperty() method allows you to define a new property on an object, including its key and value. The first argument is the object you want to add the property to, followed by the key name and an object containing the property's value. In this example, we define a new property called 'dynamicKey' on the object 'obj', with the value 'value'.

Method 3: ES6 Map()


let key = "dynamicKey";
let map = new Map();
map.set(key, "value");
console.log(map.get("dynamicKey")); // Output: "value"

The ES6 Map object allows you to use any value, including objects and functions, as keys. To add a new key-value pair to a Map, use the set() method with the key and value as arguments. In this example, we create a new Map object called 'map', and use the set() method to add the key-value pair 'dynamicKey'-'value'.

Conclusion

Using a dynamic variable as an object key in Javascript can be accomplished in multiple ways, including the bracket notation, Object.defineProperty(), and ES6 Map. Each method has its own advantages and disadvantages, so choose the one that best fits your needs.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe