Mike Manfrin Mike Manfrin - 1 year ago 62
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)?

Answer Source

Computed property names, starting from ES2015 aka ES6.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download