Mike Manfrin Mike Manfrin - 2 months ago 6
Javascript Question

Is there any clean way of initializing an object with a variable key?

I have two variable,

attribute
(e.g. "type") and
value
(e.g. "car"). I want to make an object where the key is the attribute (and the value is the value). Like this:
{"type": "car"}
.

When I do

let obj = { attribute: value }


I get

> {"attribute": "car"}


This is easy with two lines, as I can just

let obj = {};
obj[attribute] = value;


However, I'm wondering if there is a clean way of doing this in one line (since I'm a former Rubyist and I like making things clean and precise)?

Answer

Computed property names, starting from ES2015 aka ES6.

let a = "type", b = "car";
console.log({[a]: b});

Comments