javascript - How can I count how many of five properties in an object are non-null? -
i have object test represented typescript interface:
interface iwordform { definition: string; sample1: string; sample2: string; sample3: string; sample4: string; sample5: string; }
what need create function return count based on how many of sample1, sample2, sample3, sample4 , sample5 defined not null;
i think using series of if statements there clean way using modern browser function?
interfaces ain't there @ runtime, cannot use object.keys(). use explicit list of keys want check.
var count = ["definition", "sample1", "sample2", "sample3", "sample4", "sample5"].filter(k => k in obj && obj[k] != null).length;
or this:
var iwordformnonnullkeys = array.prototype.filter.bind( ["definition", "sample1", "sample2", "sample3", "sample4", "sample5"], function(k){ return k in && this[k] != null } //here can't use lambda-expression ); var count = iwordformnonnullkeys(someobj).length
why can't use object.keys()
because there no such thing interface @ runtime.
var obj = { //interface part definition: null, sample1: null, sample2: null, sample3: null, sample4: null, sample5: null, //non-interface-properties lorem: 13, ipsum: 14, dolor: 15, sit: 16, }
obj matches interface, wherever pass it.
object.keys() test non-interface-properties , count 4 in case. although non of interface-properties has non-null value.
edit: wrong.
can use object.keys(), if have filter, matches keys of interface.
var isvalidkey = /^(?:sample[1-5]|definition)$/; var count = object.keys(obj).filter(k => isvalidkey.test(k) && obj[k] != null).length
Comments
Post a Comment