← #36 Enforce required parameters
#37

Create an object with dynamic keys

Topics: JavaScript

We often use the bracket notation to add a dynamic key to an object.

const key = 'ages';
const person = {
name: 'John Doe',
};

person[key] = 42;

ES6 allows us to do that in a declarative way as following:

const key = 'ages';
const person = {
name: 'John Doe',
[key]: 42,
};

Here is a simple usage. The sample code below returns the list of name and value of given input fields in a form:

// `formEle` is the form element
const data = [...formEle.querySelectorAll('input')].map(field => {
return {
[field.getAttribute('name')]: field.getAttribute('value'),
};
});
Fix a typo or suggest an improvement
#38 Return an object in an arrow function quickly