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

Get the total number of specific key of an associative array

请问如何获得此类记录中所有 "COLOR: RED" 的计数? 实际上数据是一个 firebase json object

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;

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

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
  }
};

然后你可以用这样的东西来计算颜色=红色的对象的数量:

// 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"

请注意,选择好的变量名对于理解您编写的代码至关重要。所以在上面的代码片段中,我已经用 data 替换了你的 myArray,因为(正如一些评论者指出的那样)你的数据结构不是数组。我还建议将通用 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);

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

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