javascript - Recursive method for checking an object -


so have created constructor attempting prototype. want method checks through each property in object see if empty , if returns key. if property object want check through sub object well.

updated:

my code far:

function properties(val1, val2, val3, val4){     this.prop1 = val1 || "";     this.prop2 = val2 || "";     this.prop3 = val3 || "";     this.prop4 = val4 || {}; }  properties.prototype = {     isempty: function(){         (key in this) {             if(typeof this[key] == "object" && this[key] !== null){                 this[key].isempty();             } else {                 if(!this[key]){                     console.log(key);                 }             }         }     } }  var test = new properties("something", "", "", {subprop1: "something else", subprop2: "",   subprop3: {subsubprop1: "", subsubprop2: "" }}); 

the method should return prop2, prop3, subprop2, subsubprop1, subsubprop2

that method isn't property on object. need pass in object in question. can pass array in keep track of empty keys:

var emptykeys = []; function isempty(obj, keysarr) {     (var key in obj) {         if (typeof obj[key] === "object" && obj.hasownproperty(key)) {             isempty(obj[key], keysarr);         } else {             if (obj[key] == "" || obj[key] == null) {                 keysarr.push(key);             }         }     } } 

demo: http://jsfiddle.net/17rt0qy3/1/

if want on actual object, add above function inside isempty function:

isempty: function(){     var emptykeys = [];     amiempty(this, emptykeys);      return emptykeys;      //actual logic     function amiempty(obj, keysarr) {         (var key in obj) {             if (key == "isempty") {                 continue;             }              if (typeof obj[key] === "object" && obj.hasownproperty(key)) {                 amiempty(obj[key], keysarr);             } else {                 if (obj[key] == "" || obj[key] == null) {                     keysarr.push(key);                 }             }         }              }  } 

demo: http://jsfiddle.net/17rt0qy3/2/

and fiddle working demo object above: http://jsfiddle.net/17rt0qy3/3/

aaand edit, this log keys, but it's bit cleaner:

isempty: function(obj, keys) {     keys = keys || [];     obj = obj || this;     (var key in obj) {         if (typeof obj[key] === "object" && obj.hasownproperty(key)) {             this.isempty(obj[key], keys)         } else {             if (obj[key] == "" || obj[key] == null) {                 keys.push(key);             }         }     }      return keys;  } 

demo: http://jsfiddle.net/17rt0qy3/8/


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -