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

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -