Simplest way to get count of keys with a particular value

前端 未结 4 522
太阳男子
太阳男子 2021-01-25 05:34

Given a javascript object, what is the simplest way to get the number of keys with a particular value?

For example, I have the following javascript obje

相关标签:
4条回答
  • 2021-01-25 06:09

    Just filter and get the length.

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

    0 讨论(0)
  • 2021-01-25 06:15
    function countKeys(data, expected) {
      return Object.keys(data).map(key => data[key] == expected).reduce((p, c) => p + c, 0);
    }
    

    Take the object's keys, compare each one and convert to a boolean, then add the booleans together (coerces them to 0 for false, 1 for true, and sums).

    With ES5, breaking this down, you can:

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

    or with the even-older loops:

    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;
    }
    
    0 讨论(0)
  • 2021-01-25 06:19

    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')

    0 讨论(0)
  • 2021-01-25 06:20

    You would use Object.keys and 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;
    
    0 讨论(0)
提交回复
热议问题