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