Counting Occurrences of Object Values

前端 未结 2 2046
刺人心
刺人心 2021-01-03 10:11

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         


        
相关标签:
2条回答
  • 2021-01-03 10:26

    Nevermind, long day.

    I noticed I forgot to access the property city

    The Fix: obj[json[i].city]

    Thanks!

    0 讨论(0)
  • 2021-01-03 10:41

    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.

    0 讨论(0)
提交回复
热议问题