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

Learn how to use a variable for a key in 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' }

Hope you found this post useful. It was published . Please show your love and support by sharing this post.