I am trying to loop through some data in a JSON file and count the number of same cities/occurrences...
var json = [
{ \"city\": \"California\" },
{ \"ci
Nevermind, long day.
I noticed I forgot to access the property city
The Fix: obj[json[i].city]
Thanks!
An alternate way of phrasing this:
json.reduce(function(sums,entry){
sums[entry.city] = (sums[entry.city] || 0) + 1;
return sums;
},{});
Array.reduce() calls a callback on each element of the array, passing the return of the previous call in as the first parameter in the next. (The {}
at the end is the initial value, passed into the first call)
So this is doing exactly what you did - creating an empty object, iterating through the array, and accumulating totals inside the object. It's just doing it tersely.