I am trying to write a recursive function that essentially drills down an object looking for a specific key. Once that key is found I would like to rename that object key and keep the original contents and continue to iterate through that found key's value (array of objects) looking for the same key if present.
const data = {
"name": "lorem",
"folders": [
{
"name": "ipsum",
"folders": [
{
"name": "inner ipsum",
"folders": [
{
"name": "first nested"
},
{
"name": "second nested"
}
]
}
]
},
{
"name": "dolor",
"folders": [
{
"name": "first inner dolor"
},
{
"name": "second inner dolor",
"folders": [
{
"name": "test"
}
]
}
]
}
]
}
// recursive function that looks for key === "folders" within obj and renames to "items"
// continues to search within "items" value for the same "folders" key to repeat the process of // renaming the obj
const recursivelyGetAllFolders = (obj) => {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (key === "folders") {
// keep contents of folders obj, but rename key to "items"
obj["items"] = obj["folders"];
// call function recursively to iterate through again?
if (obj["items"] && typeof obj["items"] === "object") {
const result = recursivelyGetAllFolders(folder["items"]);
if (result) {
return result;
}
} else {
return obj;
}
}
}
}
}
recursivelyGetAllFolders(data);