计算重复数组中的JavaScript对象值

时间:2015-12-08 19:05:37

标签: javascript arrays javascript-objects

您好我是社区的新手,这是我的第一个问题。

///我有一个对象数组。在某些时候会是几百。

var locations = [{
    "name": "Costco",
    "city": "San Francisco",
    "state": "CA",
    "zip": "75201",
}, {
    "name": "Safeway",
    "city": "Appleton",
    "state": "WI",
    "zip": "90210",
}, {
    "name": "Foodmart",
    "city": "Orlando",
    "state": "FL",
    "zip": "90210",
}, {
    "name": "Trader Joes",
    "city": "Concord",
    "state": "CA",
    "zip": "90210",
}];

///我需要计算每个"状态:"并将值保存为变量,如下所示。

var CA
/// Value would be 2

var FL
/// Value would be 1

var WI
/// Value would be 1 

///原谅我,我对阵列

有点生疏了

2 个答案:

答案 0 :(得分:6)

使用简单的循环,您可以执行此操作。 (这使用ES6箭头函数语法,并且。使用var和匿名函数语法轻松替换旧浏览器兼容性)

let states = {};

locations.forEach(obj => {
    if (states[obj.state]) states[obj.state]++;
    else states[obj.state] = 1;
});

循环遍历数组,检查计数器对象中是否存在条目,如果存在,则递增计数,否则添加条目并将其设置为1.

请注意,我使用了一个对象来存储计数,而不是单个变量。通过这种方式索引更简洁,更容易。

答案 1 :(得分:0)

感谢" Sterling Archer" ......这已经解决了。 小提琴:http://jsfiddle.net/30bdf7h2/48/

// LIST

var locations = [{
  "name": "Costco",
  "city": "San Francisco",
  "state": "CA",
  "zip": "75201",
}, {
  "name": "Safeway",
  "city": "Appleton",
  "state": "WI",
  "zip": "90210",
}, {
  "name": "Foodmart",
  "city": "Orlando",
  "state": "FL",
  "zip": "90210",
}, {
  "name": "Trader Joes",
  "city": "Concord",
  "state": "CA",
  "zip": "90210",
}];

var states = {};
locations.forEach(obj => {
  if (states[obj.state]) states[obj.state]++;
  else states[obj.state] = 1;
});

var countForCA = states["CA"];

magic();
function magic() {
  document.getElementById("state_total").innerHTML = "CA Count: "+countForCA;
  document.getElementById("array_total").innerHTML = "Array Total: " + locations.length;
}