Create an object using dynamic keys
Here is a function that builds the object dynamically:
function onEntry(key, value) {
console.log(key) // productName
console.log(value) // Budweiser
const obj = { key: value }
console.log(obj) // { key: "Budweiser" }
}
Expected Result
{ productName: "Budweiser" }
But the property name is not evaluated
{ key: "Budweiser" }
How do I make the property name of an object evaluate to an expression ?
+3
source to share
1 answer
Create an object and set its key manually.
var obj = {}
obj[key] = value
Or, using ECMAScript 2015 syntax , you can also do this directly in the object declaration:
var obj = {
[key] = value
}
+3
source to share