Creating Objects with Dynamic Property Keys in Javascript (ES6 Way)

Published on July 17, 2019

Use-Cases of this Tutorial

  • Create an object property key whose name should be set as the value of a given variable.

ES6 has brought "Computed property names" that helps in creating an object with dynamic property names. The new object is created normally, the only difference being is that the dynamic key value is to be put between square brackets [ ].

// dynamic property key name
var type = 'name';

// set dynamic property between square brackets
var o = {
	id: 1131,
	gender: "Male",
	[type]: "Sample Name"
}

// { id: 1131, gender: "Male", name: "Sample Name" }
console.log(o);

You can even put an entire expression between the brackets.

var i = 1000;
var type = 'name';

var o = {
	[type + '_' + i++]: "One",
	[type + '_' + i++]: "Two",
	[type + '_' + i++]: "Three",
}

// { name_1000: "One", name_1001: "Two", name_1002: "Three" }
console.log(o);
Loading Comments