I've got a small bit of code I'm having a hell of a time with.
The function traverses through a data object successfully however I'm having trouble storing the results in a variable as the function calls itself and resets the variable.
function breadcrumb(data) {
var results = new Array();
for (var key in data) {
// Ignore prototype
if (!data.hasOwnProperty(key)) continue;
// Remove empty values
if (data[key] === null) delete data[key];
// Find only keys that match
if (key === "parent_element") {
var obj = data[key];
console.log(data);
results.push(data);
// Traverse
breadcrumb(obj);
}
}
return results;
}
breadcrumb(data.wordpressPage);
The console log gives me the data I need. I've considered and looked at passing the variable from outside the function but haven't had any luck.
Any pointers as to how I can create a new object or array from the results of the function would be much appreciated.
results.push(...breadcrumb(obj));orresult = result.concat(breadcrumb(obj));instead ofbreadcrumb(obj);? After all,breadcrumbreturns your results. You’re not doing anything with this result by just calling the function. The scope ofvar resultsis limited to the current call.