0

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)?

Mike Manfrin
  • 2,722
  • 2
  • 26
  • 41

1 Answers1

1

Computed property names, starting from ES2015 aka ES6.

let a = "type", b = "car";
console.log({[a]: b});
ASDFGerte
  • 4,695
  • 6
  • 16
  • 33