How To Set Dynamic ObjectProperty Keys in JavaScript ES6
Jun 14, 2021
Javascript expects strings as object keys.
const myObj = {
key1: 'property1'
}
What if I want my key to be dynamically set?
const myArr = ['all', 'your', 'base'];
let myObj = {};myArr.forEach(item => {
myObj = {...myObj, item: 'property1'};
})console.log(myObj);// This code will create an object with 'item' as the key, not the items found in the array, as we want.
The solution
The solution is quite simple. Simply add a square bracket when setting the key.
const myArr = ['all', 'your', 'base'];
let myObj = {};myArr.forEach(item => {
myObj = {...myObj, [item]: 'property1'};
})console.log(myObj);
Happy Coding!