0

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!

1
  • myArray.push( { [name] : { [fruit] : fruitcolor } }). Use bracket notation. Commented Oct 9, 2021 at 14:27

1 Answer 1

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.