How To Set Dynamic ObjectProperty Keys in JavaScript ES6

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!

FullStack Dev. Working to bring acts of goodness and kindness to the world.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How To Correctly Set Up TypeScript Project References In A Monorepo

How To Use Google Assistant To Get Your Latest WordPress Post

How to build a shopping cart using DragsterJS and JavaScript?

RE Challenge Part 1

Setting up Phaser 3 with Webpack and NodeJS — Part II

Why we chose Vue.js for an auto insurance purchasing service interface

Angular Router And Its Essential

Bit Manipulation

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mendel Bakaleynik

Mendel Bakaleynik

FullStack Dev. Working to bring acts of goodness and kindness to the world.

More from Medium

Understanding Javascript imports and exports

What is hoisting in Javascript?

What is the difference between Typescript and Javascript?

typescript vs javascript

Dealing With Date Serialization And Deserialization In JavaScript