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?

3
  • ` var tmp = {};tmp[k]=v;` Commented Jun 22, 2015 at 22:00
  • You should use bracket notation as described here. Commented Jun 22, 2015 at 22:00
  • Please use the search before you ask a new question. Commented Jun 22, 2015 at 22:13

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.