GalaxyCat
GalaxyCat

Reputation: 17

How to query a key via a variable?

I want to set the value of a JSON key by a variable to setCache with the star and then the function sets the key value in the JSON object cache.

I have code it how I think it makes sense, however I know this is wrong because star is not in the object.

I also thought of using template strings.

My code

var cache = {
    "capricorn": "this should be null",
    "aquarius": "null",
    "pisces": "null",
    "aries": "null",
    "taurus": "null",
    "gemini": "null",
    "cancer": "null",
    "leo": "null",
    "virgo": "null",
    "libra": "null",
    "scorpio": "null",
    "ophiuchus": "null",
    "sagittarius":"null"
}

function setCache(cache,star, value) {
    cache.star = value
}

Upvotes: 1

Views: 54

Answers (1)

Mureinik
Mureinik

Reputation: 311563

You can use the subscript ([]) operator to refer to a property using a variable:

cache[star] = value;

Upvotes: 1

Related Questions