计算对象值的出现次数 [英] Counting Occurrences of Object Values

查看:76
本文介绍了计算对象值的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历JSON文件中的一些数据并计算相同城市/事件的数量...

I am trying to loop through some data in a JSON file and count the number of same cities/occurrences...

var json = [
  { "city": "California" },
  { "city": "California" },
  { "city": "California" },
  { "city": "Texas" },
  { "city": "Florida" }
];

var obj = {};

for (var i = 0, j = json.length; i < j; i++) {
  if (obj[json[i]]) {
    obj[json[i]]++;
  }
  else {
    obj[json[i]] = 1;
  } 
}

console.log(obj);

JSFiddle: http://jsfiddle.net/f2939ucw/

问题是返回的对象只返回返回数组中的对象数,而不是相同的城市数。

The problem is that the object returned is only returning back the number of objects within the array and not the same occurrences of cities.

推荐答案

另一种表达方式:

json.reduce(function(sums,entry){
   sums[entry.city] = (sums[entry.city] || 0) + 1;
   return sums;
},{});

Array.reduce() 在数组的每个元素上调用回调,将前一次调用的返回作为下一个中的第一个参数传递。 (最后的 {} 是初始值,传入第一次调用)

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.

这篇关于计算对象值的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆