Reputation: 39
I have a code
var myArray = []
myArray.push( { "bob" : { "banana" : "yellow" } })
console.log(myArray)
which returns
{
"bob": {
"banana": "yellow"
}
}
Now, I want to change the variables like this:
var myArray = []
var name = "bob"
var fruit = "banana"
var fruitcolor = "yellow"
myArray.push( { name : { fruit : fruitcolor } })
console.log(myArray)
but it doesn't return the same result. How do I fix this?
Thanks!
Upvotes: 0
Views: 24
Reputation: 1362
If you want to set a string as a key of an object you have to use bracket notation
Replace
myArray.push( { name : { fruit : fruitcolor } })
with :
myArray.push( { [name] : { [fruit] : fruitcolor } })
Upvotes: 1