获取关联数组的特定键的总数

时间:2015-01-20 21:56:43

标签: jquery arrays angularjs firebase

请问我如何得到所有" COLOR:RED"在这种类型的记录? 实际上数据是firebase json对象

myarray =
    {
      "CAR": {
        "COLOR": "RED",
        "ID": "41.203.65.171",
        "rating": 5
      },
      "BIKE": {
        "COLOR": "BLUE",
        "ID": "41.203.65.171",
        "rating": 8
      },
      "PLANE": {
        "COLOR": "RED",
        "ID": "41.203.65.171",
        "rating": 3
      },

我试过这个:

var count = 0;
jQuery.each(myarray, function (key, value) {
    if (key == "COLOR" && value == "RED")) {
        counts[value]++;
    } else {
        counts = 0;
    }
});

以上是错误的,这是我需要帮助的,

我希望有点像red = 2;

2 个答案:

答案 0 :(得分:1)

如果我们从这样的对象开始:

var data = {
  "CAR": {
    "COLOR": "RED",
    "ID": "41.203.65.171",
    "rating": 5
  },
  "BIKE": {
    "COLOR": "BLUE",
    "ID": "41.203.65.171",
    "rating": 8
  },
  "PLANE": {
    "COLOR": "RED",
    "ID": "41.203.65.171",
    "rating": 3
  }
};

然后你可以用这样的东西计算COLOR = RED的对象数量:

// First determine all the vehicletypes in an array
var vehicleTypes = Object.keys(data); // [ "CAR", "BIKE", "PLANE" ]

// Next, filter that array to only contain the RED vehicle types: [ "CAR", "PLANE" ]
var redVehicleTypes = vehicleTypes.filter(function(vehicleType) { 
  return data[vehicleType].COLOR == "RED" 
});

// Finally, count the number of elements in the array
var redVehicleCount = redVehicleTypes.length;

请注意,此解决方案不使用jQuery,Firebase或Angular。

更新

使用jQuery并且更接近您的尝试的解决方案:

var count = 0;
jQuery.each(data, function (key, value) {
    if (value["COLOR"] == "RED") {
        console.log("The "+key+" is red");
        count++;
    }
});
console.log(count);

最大的变化是在车辆上实现each循环,因此您只需检查value["COLOR"] == "RED"

请注意,选择好的变量名称至关重要,以便能够理解您编写的代码。因此,在上面的代码段中,我已将myArray替换为data,因为(正如一些评论者指出的那样)您的数据结构不是数组。我还建议将通用keyvalue更改为vehicleTypevehicleData

var count = 0;
jQuery.each(data, function (vehicleType, vehicleData) {
    if (vehicleData.COLOR == "RED") {
        console.log("The "+vehicleType+" is red");
        count++;
    }
});
console.log(count);

答案 1 :(得分:0)

一种方法是创建一个使用颜色作为键的简单对象,并将其计为值

var colors ={};

jQuery.each(myarray, function (key, value) {
     var currColor = myarray[key].COLOR;
     /* add color as property if it doesn't already exist */
     if(!colors[ currColor ] ){
         colors[ currColor ] = 0;
      }
      /* increment count for the color */
      colors[ currColor ] ++;
});

console.log(colors)
// returns  {"RED": 2,"BLUE": 1}
alert(colors.RED) // 2

DEMO