3

Here is a function building an object dynamically:

function onEntry(key, value) {
  console.log(key) // productName
  console.log(value) // Budweiser

  const obj = { key: value }
  console.log(obj) // { key: "Budweiser" }
}

Expected output is

{ productName: "Budweiser" }

But property name is not evaluated

{ key: "Budweiser" }

How to make property name of an object evaluated as an expression?

kube
  • 13,176
  • 9
  • 34
  • 38
David Ott
  • 43
  • 7

1 Answers1

3

Create an object, and set its key manually.

var obj = {}
obj[key] = value

Or using ECMAScript 2015 syntax, you can also do it directly in the object declaration:

var obj = {
  [key] = value
}
kube
  • 13,176
  • 9
  • 34
  • 38