获取具有特定值的键的最简单方法

时间:2016-01-12 16:49:58

标签: javascript

给定一个javascript对象,获取具有特定值的键数的最简单方法是什么?

例如,我有以下javascript对象(其中键表示测试脚本ID,值表示脚本执行的结果):

var result = {1: "PASS", 2: "PASS", 3: "FAIL", 4: "PASS", 5: "FAIL"};

我想以最简单的方式获得值为“PASS”(在这种情况下为3)的键计数。

4 个答案:

答案 0 :(得分:1)

function countKeys(data, expected) {
  return Object.keys(data).map(key => data[key] == expected).reduce((p, c) => p + c, 0);
}

object's keys,比较每一个并转换为布尔值,然后将布尔值加在一起(将它们强制为0表示为假,1表示为真,以及总和)。

使用ES5,打破这个,你可以:

function countKeys(data, expected) {
  var keys = Object.keys(data);
  var checked = keys.map(function (key) {
    return data[key] == expected;
  });
  return checked.reduce(function (prev, cur) {
    return prev + cur;
  }, 0);
}

或使用更老的循环:

function countKeys(data, expected) {
  var keys = Object.keys(data);
  var count = 0;
  for (var i = 0; i < keys.length; ++i) {
    var value = data[key];
    if (value == expected) {
      ++count;
    } else {
      // do nothing or increment some failed counter
    }
  }
  return count;
}

答案 1 :(得分:1)

只需过滤并获得长度。

var result = { 1: "PASS", 2: "PASS", 3: "FAIL", 4: "PASS", 5: "FAIL" };

function getCount(s, o) {
    return Object.keys(result).filter(function (k) { return o[k] === s; }).length;
}

document.write(getCount('PASS', result));

答案 2 :(得分:1)

您将使用Object.keys和Array.filter:

var result = {1: "PASS", 2: "PASS", 3: "FAIL", 4: "PASS", 5: "FAIL"};
var passCount = Object.keys(result).filter(function(key){
   return ( result[key] === 'PASS' );
}).length;

答案 3 :(得分:0)

var result = {1: "PASS", 2: "PASS", 3: "FAIL", 4: "PASS", 5: "FAIL"};

undefined

function getCountByValue(obj,value){
  return Object.keys(result).filter(function(key){
  return result[key] === value

}).length

}

//as your wish
getCountByValue(result,'FAIL')
getCountByValue(result,'PASS')