1

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
}
Gass
  • 7,536
  • 3
  • 37
  • 41
GalaxyCat
  • 17
  • 1
  • 10
  • Does this answer your question? [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – VLAZ Sep 08 '21 at 18:22

1 Answers1

1

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

cache[star] = value;
Mureinik
  • 297,002
  • 52
  • 306
  • 350