Esc6 object part 2

Computed Property Names



With ES6, you can now use computed property names. Using the square bracket notation [], we can use an expression for a property name, including concatenating strings. This can be useful in cases where we want to create certain objects based on user data (e.g. id, email, and so on).

Here are three examples:
Example 1:
let prop = 'name';
let id = '1234';
let mobile = '08923';

let user = {
[prop]: 'Jack',
[`user_${id}`]: `${mobile}`
};
Try It Yourself

Example 2:
var i = 0;
var a = {
['foo' + ++i]: i,
['foo' + ++i]: i,
['foo' + ++i]: i
};
Try It Yourself

Example 3:
var param = 'size';
var config = {
[param]: 12,
['mobile' + param.charAt(0).toUpperCase() + param.slice(1)]: 4
};
console.log(config);
Try It Yourself

It is very useful when you need to create custom objects based on some variables.

Comments