Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dennythecoder/5e92615ab22ea2f62b6ca36d1e5096e8 to your computer and use it in GitHub Desktop.
Save dennythecoder/5e92615ab22ea2f62b6ca36d1e5096e8 to your computer and use it in GitHub Desktop.
//https://stackoverflow.com/questions/79591547/unknown-json-stringify-issue
if (localStorage.balances == undefined) {
localStorage.setItem('balances', '{"ffdbddfaae": "0"}') // initialize balance so JSON doesn't error out
}
let balances = JSON.parse(localStorage.balances) // convert string to JSON object for further changes
let addToBalance = function(value, id) {
let key = id.replace(/[0-9]/g, '') // convert alphaumerical id string to only letters to not cause errors when using balances.(id)
if (key in balances) { // convert alphaumerical id string to only letters to not cause errors when using balances.(id) and check if id exists in balance object
balances[key] += value
} else {
balances[key] = value
}
localStorage.setItem("balances", JSON.stringify(balances))
}
addToBalance(100, "ffdbddfaae")
addToBalance(69, "foobarid")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment