How to Set an Object Key Using a Variable in JavaScript
How can we set an object key using a variable in JavaScript?
Suppose we have an object obj
.
const obj = {};
Let’s say we want to use the output of uuid()
as our key.
import { v4 as uuidv4 } from 'uuid';
const id = uuidv4(); // '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
We want our object to look like this:
const obj = {
'9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d': 0,
'1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed': 0,
}
And not like this:
const obj = {
id: 0,
}
Use Computed Property Names (bracket notation)
In ES6, we can use Computed Property Names.
const id = uuidv4();
const obj = {
[id]: 0
};
We can place expressions inside the brackets, and it will be computed and used as the property name.
Add key-value pair after initialization
In ES5, we can simply create the object and then add the key-value pair after initialization.
const id = uuidv4();
const obj = {};
obj[id] = 0;