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
}
CodePudding user response:
You can use the subscript ([]
) operator to refer to a property using a variable:
cache[star] = value;