Skip to content

Latest commit

 

History

History
38 lines (31 loc) · 733 Bytes

create-an-object-with-dynamic-keys.mdx

File metadata and controls

38 lines (31 loc) · 733 Bytes
category created tags title
Tip
2021-02-25
JavaScript
Create an object with dynamic keys

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'),
    };
});