Javascript - Object Literal with dynamic field names

Introduction

You can use dynamic field names in an object literal:

const field = 'Book'; 
const price = 5.99; 
const count = 2; 
const myOrder = { 
        [field]: price, 
        count, 
        getTotal() { 
                return this.price * this.count; 
        } 
}; 
console.log(myOrder); 

The field in the object gets assigned the name dynamicField.

You can create a dynamic field name in a method as well. They work with setters and getters as well.

You can actually use an entire expression and make naming properties even more dynamic:

const field = 'Book'; 
const price = 5.99, count = 2; 
const myOrder = { 
        [field + "-01"]: price, 
        count, 
        getTotal() { 
                return this.price * this.count; 
        } 
}; 
console.log(myOrder); 

Related Topic