Skip to content
the poor coder

javascript variable as object key

Poor Man
Published
Reading time
2 min read
On this page

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#

Text

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()#

Text

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()#

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC