sav vv sav vv - 1 year ago 46
Javascript Question

return object length which includes key is true not false

I want to write some filter logic where an object returns its length which includes only key having true value.

$scope.generated.codesWithBalance = [A:true, B:true, C:false];

so for above object it should return length as 2. Since C is false so want to exclude in the count.

But now whenever i try to get the length it returns total length


Any way that i can avoid key having false value?

Answer Source

Use Array.prototype.filter() to get only the keys with true values.

Object.keys($scope.generated.codesWithBalance).filter(function(key, i, array) {
    return array[key];