I am faced with a JavaScript object that contains various data:
{
"gender": "man",
"jobinfo": {
"type": "teacher"
},
"children": [
{
"name": "Daniel",
"age": 12,
"pets": [
{
"type": "cat",
"name": "Willy",
"age": 2
},
{
"type": "dog",
"name": "Jimmie",
"age": 5
}
]
}
]
}
My goal is to list out all the paths (keys and array indices) within the object, including their respective parents (e.g., children
should be included along with its contents).
gender
jobinfo,
jobinfo.type,
children,
children.0.name,
children.0.age,
children.0.pets,
children.0.pets.0.type,
children.0.pets.0.name,
children.0.pets.0.age,
children.0.pets.1.type,
children.0.pets.1.name,
children.0.pets.1.age
I attempted to write a code for this purpose but encountered issues:
function getPath(object) {
for (key in object) {
if (Array.isArray(object[key]) === true) {
console.log(key)
getPath(object[key])
} else if (typeof object[key] === 'object') {
console.log(key)
getPath(object[key])
} else {
console.log(key)
}
}
}
While this code does display all keys in the JSON object, I am finding it challenging to concatenate the paths, particularly in nested elements.