Skip to content

Instantly share code, notes, and snippets.

@deepaknverma
Created May 28, 2017 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deepaknverma/16b07dbcb3d7eea2bc86934dd7e0fe40 to your computer and use it in GitHub Desktop.
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
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