Created
May 28, 2017 07:41
-
-
Save deepaknverma/16b07dbcb3d7eea2bc86934dd7e0fe40 to your computer and use it in GitHub Desktop.
recursively loop through object keys at root and output tree path from root to leaf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let getPaths = (object) => { | |
var result = []; | |
// Can't pass null here | |
if (object === null) { | |
return; | |
} | |
// Creating local array | |
if(!currentVal) { | |
var currentVal = []; | |
} | |
for (var property in object) { | |
if (object.hasOwnProperty(property)) { | |
if (typeof object[property] === 'object') { | |
currentVal.push(scrape(object[property], null, null)); | |
} else { | |
currentVal.push(object[property]); | |
} | |
} | |
} | |
return currentVal; | |
} | |
let scrape = (object, currentVal) => { | |
// Can't pass null here | |
if (object === null) { | |
return; | |
} | |
// Creating local array | |
if(!currentVal) { | |
var currentVal = []; | |
} | |
// console.log(object) | |
for (var property in object) { | |
if (object.hasOwnProperty(property)) { | |
if (typeof object[property] === 'object') { | |
scrape(object[property], currentVal); | |
} else if(object[property]) { | |
thisVal = object[property]; | |
currentVal.push(object[property]); | |
} | |
} | |
} | |
return currentVal; | |
} | |
var thisObject = { | |
"l": { | |
"l": { | |
"l": { | |
"l": null, | |
"r": null, | |
"x": 5 | |
}, | |
"r": null, | |
"x": 4 | |
}, | |
"r": null, | |
"x": 5 | |
}, | |
"r": { | |
"l": { | |
"l": null, | |
"r": null, | |
"x": 1 | |
}, | |
"r": { | |
"l": null, | |
"r": null, | |
"x": 6 | |
}, | |
"x": 6 | |
}, | |
"x": 4 | |
}; | |
console.log(getPaths(thisObject)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment