I'm fetching data from this specific data:
{"cookie-stats": {"eating": 2, "5-minutes-ago": "-2"}
I'm currently doing this:
{cookies['cookie-stats'].5-minutes-ago}
However, I keep getting the error: Syntax error: Unexpected token, expected "}"
How do I get the value of "5-minutes-ago" when I'm fetching data?
CodePudding user response:
To take the value of such a crazy prop that contains dash and numbers, you must use square brackets.
You should do something like that.
let res = {"cookie-stats": {"eating": 2, "5-minutes-ago": "-2"}}
console.log(res['cookie-stats']['5-minutes-ago'])
CodePudding user response:
You could also do this:
const cookies = {
"cookies": {
"eating": 2,
"fiveMinutesBefore": "-2",
}
}
console.log(cookies.cookies.fiveMinutesBefore);
If you just change your naming convention it would solve your issue. The answer above is great too, but if you're looking to play around with dot notation this is the best way IMO. The issue was that when you were trying to use .5-minutes-before it was not reading that key as a string, but instead the 5 was read as a Number.