Traversing nested javascript object to identify empty value properties -


if had object:

var dog= {   name: "max",   age: 5,   sex: undefined,   details: {     color: "black",     breed: undefined   } } 

and wanted paths of properties undefined values. how iterate through of properties, including nested ones?

currently, have vanilla js method object without nested properties:

function getundefinedpaths(o, name) {   var paths = [];   (var prop in o) {     if (o[prop] === undefined) {         paths += name + "." + prop + "\n";     }   }   return paths; }  // getundefinedpaths(dog, "dog") returns "dog.sex" , not "dog.details.breed" undefined. 

i'm stuck. can out on how paths of undefined values in nested property of js object? i'm attempting in vanilla javascript only. in advance.

you can use recursive function so:

function getpath(obj, path) {      var props = [];          for(var key in obj) {          if(obj[key] === undefined) {             props.push(path + '.' + key);         }          if(obj[key] instanceof object) {             props.push.apply(props, getpath( obj[key], path + '.' + key ));         }      }      return props; }   var path = getpath(dog, 'dog'); 

this return array of paths undefined properties

you can use join on resulting 'array' string if necessary:

console.log(path.join('\n')); 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -