Computed property names

Defination

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed as the property name. This is symmetrical to the bracket notation of the property accessor syntax, which you might have used to read and set properties already. Now you can use the same syntax in object literals, too

Syntax

1
// Computed property names (ES2015)
2
var i = 0;
3
var a = {
4
};
5
6
console.log(a.foo1); // 1
7
console.log(a.foo2); // 2
8
console.log(a.foo3); // 3
9
10
var param = 'size';
11
var config = {
12
};
13
14
console.log(config); // {size: 12, mobileSize: 4}
Copied!

Usage

1
class Reservation extends React.Component {
2
constructor(props) {
3
super(props);
4
this.state = {
5
isGoing: true,
6
numberOfGuests: 2
7
};
8
9
this.handleInputChange = this.handleInputChange.bind(this);
10
}
11
12
handleInputChange(event) {
13
const target = event.target;
14
const value = target.type === 'checkbox' ? target.checked : target.value;
15
const name = target.name;
16
17
this.setState({
18
[name]: value
19
});
20
}
21
22
render() {
23
return (
24
<form>
25
<label>
26
Is going:
27
<input
28
name="isGoing"
29
type="checkbox"
30
checked={this.state.isGoing}
31
onChange={this.handleInputChange} />
32
</label>
33
<br />
34
<label>
35
Number of guests:
36
<input
37
name="numberOfGuests"
38
type="number"
39
value={this.state.numberOfGuests}
40
onChange={this.handleInputChange} />
41
</label>
42
</form>
43
);
44
}
45
}
Copied!

References