Mike Manfrin Mike Manfrin - 4 months ago 15
Javascript Question

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

I have two variable,

(e.g. "type") and
(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)?


Computed property names, starting from ES2015 aka ES6.

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