Creating Objects with Dynamic Keys in Javascript (ES6 Way)

Use-Cases of this Tutorial

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

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

// the key name
var type = 'name';

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);