OB = { "138": { "img": "album_img_608842801.png", "children": { "215": { "img": "album_img_386920978.png", "children": { "217": { "name": "Veronica Zemanova", "children": { "218": { "img": "album_img_884191953.png", "children": { "226": { "img": "album_img_912163411.png", "children": { "229": { "img": "album_img_221377469.png", } } } } } } } } } } } };Código de Python que pude hacer
def recursive_items(dictionary): for key, value in dictionary.items(): if type(value) is dict: yield (key, value) yield from recursive_items(value) else: yield (key, value) for key in recursive_items(OB): print(key)¿Cómo se puede reescribir este código para js? El tamaño de la matriz es inicialmente desconocido Necesitamos obtener el resultado en la forma: [138,215,217,218,226,229] ¡Gracias a todos por las respuestas!
Similar a su solución de python, recorreremos recursivamente el objeto.
Probamos si la clave es un número, y si lo es, la entregamos, y todas las claves numéricas de sus hijos.
function* define una función generadora en JavaScript.
yield produce un nuevo valor en el generador
yield* produce todos los valores en el iterable dado. (Similar a yield from en Python, si tuviera que adivinar)
Más información en https://javascript.info/generators
const OB = { "138": { "img": "album_img_608842801.png", "children": { "215": { "img": "album_img_386920978.png", "children": { "217": { "name": "Veronica Zemanova", "children": { "218": { "img": "album_img_884191953.png", "children": { "226": { "img": "album_img_912163411.png", "children": { "229": { "img": "album_img_221377469.png", } } } } } } } } } } } }; // generator function, like python function* numberKeys(obj) { // for each key in the object for (const key in obj) { // if the key is a number if (!isNaN(key)) { // then we yield the key yield key; // then we yield all the number keys of the children yield* numberKeys(obj[key].children); } } } for (const key of numberKeys(OB)) { console.log(key); }Aquí hay otro método que usa Object.keys para devolver una matriz de claves y Array.prototype.reduce para procesarlo. Es un método similar a @kellys, pero no uso generadores (quizás debería) y pensé en dejar esto aquí en caso de que sea útil.
function pluckNumericKeys(obj, acc = []) { return Object.keys(obj).reduce((acc, key) => { if (!isNaN(key)) acc.push(key) if (typeof obj[key] === 'object') acc = pluckNumericKeys(obj[key], acc) return acc }, acc) } const OB = { "138": { "img": "album_img_608842801.png", "children": { "215": { "img": "album_img_386920978.png", "children": { "217": { "name": "Veronica Zemanova", "children": { "218": { "img": "album_img_884191953.png", "children": { "226": { "img": "album_img_912163411.png", "children": { "229": { "img": "album_img_221377469.png", } } } } } } } } } } } } const result = pluckNumericKeys(OB) console.log(result)Puede obtener recursivamente todos los valores key de los niños usando array#map y aplanar el resultado.
const OB = { "138": { "img": "album_img_608842801.png", "children": { "215": { "img": "album_img_386920978.png", "children": { "217": { "name": "Veronica Zemanova", "children": { "218": { "img": "album_img_884191953.png", "children": { "226": { "img": "album_img_912163411.png", "children": { "229": { "img": "album_img_221377469.png", } } } } } } } } } } } }; const getKeys = o => Object.keys(o).map(k => ([k, o[k].children ? getKeys(o[k].children) : []])).flat(Infinity); console.log(getKeys(OB)); .as-console-wrapper { max-height: 100% !important; top: 0; }