Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an object with dynamic keys [duplicate]

Tags:

javascript

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?

like image 530
David Ott Avatar asked Jul 24 '26 22:07

David Ott


1 Answers

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
}
like image 126
kube Avatar answered Jul 27 '26 13:07

kube