How to Add a Dynamic Property to a JavaScript Object Literal?

In this article, we're going to show you different ways of adding a dynamic property to an object literal.

Using the Computed Property Name Syntax

Starting ES6+, we can specify a dynamic object key directly in an object literal by wrapping it within square brackets. This syntax is mostly useful when adding dynamic properties to an object literal at object creation time. For example:

// ES6+
const prop = 'foo';

const obj = {
    [prop]: 'bar',
    baz: 'qux',
};

console.log(obj); // { foo: 'bar', baz: 'qux' }

Using Concatenation or String Interpolation:

It is also possible to use concatenation and/or string interpolation to create a dynamic key when using the computed property name syntax. For example:

// ES6+
const prop = 'foo';

const obj = {
    [`${prop}Bar`]: 'baz',
    ['wal' + 'do']: 'qux',
};

console.log(obj); // { fooBar: 'baz', waldo: 'qux' }

Using the Bracket Notation

Adding dynamic properties to an object literal using the bracket notation is supported across old and new browsers. This syntax is especially useful when you wish to add a dynamic property after an object has been created or when you're not using ES6. For example:

const prop = 'foo';

const obj = { baz: 'qux' };

obj[prop] = 'bar';

console.log(obj); // { baz: 'qux', foo: 'bar' }

As you can see from the example above, this syntax makes adding dynamic properties a two-step process. First, you have to create an object, and then only you can add the dynamic property to it.

Using Concatenation or String Interpolation:

It is also possible to use concatenation and/or string interpolation to create a dynamic key when using the bracket notation syntax. For example:

const prop = 'foo';

const obj = {};

obj[`${prop}Bar`] = 'baz';
obj['wal' + 'do'] = 'qux';

console.log(obj); // { fooBar: 'baz', waldo: 'qux' }

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.