Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
Cómo recorrer una matriz de objetos anidados

Me enfrento a un acertijo en el que tengo que recorrer una matriz de objetos anidados (objeto de objetos) que podrían tener otros objetos y matrices. Es decir, el arreglo tiene objetos que podrían tener otros objetos con arreglos de objetos y así sucesivamente.

La estructura de datos es para una lista (como una lista de tareas pendientes) que podría tener otra lista y esa otra lista podría tener otra lista y así sucesivamente:

 [ "Buy milk", { //<----------------- item 2 is is an object that represents sub-items itemName: "Buy Meat", //<------------ name of item 2 on list subList: [ //<------ sub-items with an item of items "Beef", { itemName: "Fish", subList: ["Tilapia", "Catfish", "Monkfish", "Halibut"] } , "Chicken", ], }, "Buy cooking oil", "Buy baking soda", { //<------------------- item 6 is an object that represents sub-items (sub-todo) itemName: "Buy Vegetable", //<------------ name of item 6 on list itemList: ["Cabbage", "Carrot", "Tomatoe", "Lettuce"] //<------ sub-items }, "Buy bread" ]

¿Cómo hago un bucle sobre una estructura de datos como esta? Además, ¿hay una mejor manera de representar esa lista?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Estás haciendo dos preguntas: primero la estructura ,

La estructura del objeto anidado debe ser consistente, por lo que la pregunta es cómo puede crear un objeto anidado donde los padres y el hijo tengan la misma estructura.

No es necesario almacenar el objeto de la misma manera que lo ve en la pantalla.

 class MyList { constructor(itemName, subList) { this.itemName = itemName; this.subList = subList; // is always of Type MyList [] } }

Con esta estructura, si SubList no está definido, es una cadena simple.

 class MyList { constructor(itemName, subList) { this.itemName = itemName; // is name of list or individual item this.subList = subList; // is always of Type MyList [] or undefined } } let list = new MyList('Buy Meat', []); // ur sublist of buyMeat list.subList.push(new MyList('beaf')); let fishList = new MyList('fish', []); // sublist fishList.subList.push(new MyList('Tilapia')); fishList.subList.push(new MyList('Catfish')); fishList.subList.push(new MyList('Monkfish')); fishList.subList.push(new MyList('Halibut')); list.subList.push(fishList); list.subList.push(new MyList('chicken')); console.log(list);
Cómo hacer un bucle . Ahora, si sigue esta estructura, notará que cada MyList se puede ver como un nodo. Y puede usar cualquier método transversal de árbol para acceder a todos los elementos. Esto se puede hacer de la forma que quieras. El siguiente ejemplo es solo la lectura de un recorrido de aproximación en profundidad de un árbol.

 class MyList { constructor(itemName, subList) { this.itemName = itemName; // is name of list or individual item this.subList = subList; // is always of Type MyList [] or undefined } } let list = new MyList('Buy Meat', []); // ur sublist of buyMeat list.subList.push(new MyList('beaf')); let fishList = new MyList('fish', []); // sublist fishList.subList.push(new MyList('Tilapia')); fishList.subList.push(new MyList('Catfish')); fishList.subList.push(new MyList('Monkfish')); fishList.subList.push(new MyList('Halibut')); list.subList.push(fishList); list.subList.push(new MyList('chicken')); // Example reading all item name: reader = (node) => node.subList ? node.subList.map(reader).flat() : [node.itemName] console.log(reader(list))

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda