你好,我是社区的新手,这是我的第一个问题.
///我有一个对象数组.在某些时候会是几百.
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", }];
///我需要计算每个"state:"并将值保存为变量,如下所示.
var CA /// Value would be 2 var FL /// Value would be 1 var WI /// Value would be 1
///原谅我,我对阵列有点生疏了
使用简单的循环,您可以执行此操作.(这使用ES6箭头函数语法,并且.使用var和匿名函数语法轻松替换旧浏览器兼容性)
let states = {}; locations.forEach(obj => { if (states[obj.state]) states[obj.state]++; else states[obj.state] = 1; });
这循环遍历数组,检查计数器对象中是否存在条目,如果存在,则递增计数,否则添加条目并将其设置为1.
请注意,我使用了一个对象来存储计数,而不是单个变量.通过这种方式索引更简洁,更容易.