Given a large JSON table in localStorage and a given key provided by the user, I access an associated value. But if the value and/or the key doesn’t exist, then I want to create them. However…
Given the following JSON:
var data = [
{ 'myKey': 'A', 'status': 0 },
{ 'myKey': 'B', 'status': 1 },
{ 'myKey': 'C' },
{ 'myKey': 'D', 'status': 1 }
];
And the following JS:
function getJsonVal(json, itemId) {
for (var i in json) {
if (json[i].myKey == itemId) {
return json[i];
}
}
}
If I…
// request non-existing-in-JSON value:
valC = getJsonVal(data, 'C');
alert("this is C's value: "+ valC)
or
// request non-existing-in-JSON key:
keyE = getJsonVal(data, 'E');
alert("this is E: "+ keyE);
the script just stop midway.
I wished to have some error value allowing me to made something like If ( null|| undefined ) Then create new key/value, but my script just stop because there these items are not existing. Any work around ? Jsfiddle appreciate.
With the typeof operator you can safely check, whether a property is set