Estoy tratando con el siguiente objeto de JavaScript:
{ "gender": "man", "jobinfo": { "type": "teacher" }, "children": [ { "name": "Daniel", "age": 12, "pets": [ { "type": "cat", "name": "Willy", "age": 2 }, { "type": "dog", "name": "Jimmie", "age": 5 } ] } ] } Quiero imprimir cada una de las rutas (claves e índices de matriz) dentro del objeto, incluidos los padres (es decir, los children deben imprimirse como todo lo que contiene).
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.ageProbé este código con modificaciones pero no funcionó para mí:
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) } } }Está imprimiendo todas las claves en JSON, pero tengo problemas para unir las rutas, especialmente en elementos anidados.
Esto funciona:
const data = {"gender":"man","jobinfo":{"type":"teacher"},"children":[{"name":"Daniel","age":12,"pets":[{"type":"cat","name":"Willy","age":2},{"type":"dog","name":"Jimmie","age":5}]}]}; const getPath = (currPath, item) => { console.log(currPath); if (Array.isArray(item)) { item.forEach((el, idx) => getPath(`${currPath}.${idx}`, el)); } else if (typeof item == "object") { Object.entries(item).forEach(([key, value]) => { getPath(`${currPath}.${key}`, value); }); } }; Object.entries(data).forEach(([key, value]) => { getPath(key, value); });Básicamente, solo recorro cada una de las entradas en el objeto inicial, usando la clave como ruta en esa etapa y verificando si el valor es un objeto o una matriz. Siempre imprimo la ruta dentro de la función (para proporcionar las capas externas que desea) y luego recurro sobre las capas internas, agregando a la ruta según sea necesario.
En esta versión, las claves de matriz que consisten en números como 'niños.0', etc., se manejan y esto da el resultado exactamente lo que quería:
const json = {"gender":"man","jobinfo":{"type":"teacher"},"children":[{"name":"Daniel","age":12,"pets":[{"type":"cat","name":"Willy","age":2},{"type":"dog","name":"Jimmie","age":5}]}]}; function getPath(object, previousPath) { for (key in object) { let currentPath = previousPath ? `${previousPath}.${key}` : key if (Array.isArray(object[key])) { console.log(currentPath) getPath(object[key], currentPath) } else if (typeof object[key] === 'object') { if (!Array.isArray(object)) { // skipping logging array keys like children.0 console.log(currentPath) } getPath(object[key], currentPath) } else { console.log(currentPath) } } } getPath(json)