Reputation: 59
I'm trying to add together a bunch of elements in a decoded JSON array:
var jqXHR = $.getJSON("data.php", function(jsonData) {
newItems = jsonData['New']['count'] || 0;
unsolvedItems = (jsonData['New']['count'] || 0)+
(jsonData['b']['count'] || 0)+
(jsonData['c']['count'] || 0)+
(jsonData['d']['count'] || 0)+
(jsonData['e']['count'] || 0)+
(jsonData['f']['count'] || 0)+
(jsonData['g']['count'] || 0);
}
As you can see, I'm trying to check if the ['count']
element exists before I try and assign the value to something, using the shorthand explained on this site, but the || 0
shorthand doesn't seem to be working. When ['New']
is not included in the JSON, I get Uncaught TypeError: Cannot read property 'count' of undefined
.
Does this not work on arrays, or am I doing it wrong? If it doesn't work, what else could I do other than resorting to a separate if statement for every element I want to use?
Upvotes: 0
Views: 1330
Reputation: 1235
the pattern that I usually opt for:
jsonData['b'] && jsonData['b']['count'] || 0
Upvotes: 0
Reputation: 382384
The problem is that you can't get jsonData['d']['count']
if jsonData['d']
is undefined
.
Your code is also full of repetitions. This kind of code is painful to maintain.
You could do it like this :
unsolvedItems = 0;
['New','b','c','d','e','f','g'].forEach(function(key){
if (jsonData[key]) unsolvedItems += jsonData[key].count || 0;
});
Upvotes: 2