In JavaScript, you can create and access object properties dynamically by using variable keys. This allows you to create more dynamic and flexible code. In this short and straightforward article, we will explore more than one way to do so.
Using bracket notation
The bracket notation allows you to use any expression as a property name, such as a variable or a string concatenation.
Example:
const obj = {
name: 'Demon of Hatred',
};
// a key can be a variable
const key = 'age';
// add a new property whose key is a variable
obj[key] = 999;
// access the property using the variable
console.log(obj[key]);
Output:
999
Using computed property names
In modern JavaScript (ES6 and above), you can use computed property names, which lets you use an expression inside square brackets after the object literal, to create or access an object’s properties by variable keys.
Example:
// define variables for the keys
const key1 = 'name';
const key2 = 'age';
// create an object with computed property names
const obj = {
[key1]: 'Sling Academy',
[key2]: 5
};
// access the properties using bracket notation
console.log(obj[key1]);
console.log(obj[key2]);
Output:
Sling Academy
5
Using Object.defineProperty()
This method can help you define a new property on an object or modify an existing one. You can use this method to create a property with a dynamic key by passing an expression as the second argument.
Example:
// the starting object
const obj = {
name: 'Voldermort',
};
// define a variable for the key
const key = 'age';
// create a property with a dynamic key and value
Object.defineProperty(obj, key, { value: 60 });
// access the property using bracket notation
console.log(obj[key]);
Output:
60
Using the Object.defineProperty() method is a little verbose because it requires a descriptor object as the third argument. In addition, it has some limitations, such as not working on non-extensible objects. I put this approach here for your preference, but I think you better use one of the first 2 approaches.
If you wonder what is a non-extensible object in JavaScript, then here’s an example:
// create an object
var obj = { name: "Wolf", age: 35 };
// make it non-extensible
Object.preventExtensions(obj);
// this throws a TypeError
Object.defineProperty(obj, "gender", { value: "male" });
console.log(obj);
// TypeError: can't define property "gender": "obj" is not extensible
The tutorial ends here. Happy coding & have a nice day!