Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
Construyendo un árbol a partir de una matriz plana

Me dan una matriz, links :

 const links = [ {parent: "flare", children: "analytics"} , {parent: "analytics", children: "cluster"} , {parent: "flare", children: "scale"} , {parent: "analytics", children: "graph"} , ];

Quiero convertirlo en un árbol, así:

 const tree = { "name": "flare", "children": [ { "name": "analytics", "children": [ { "name": "cluster", }, { "name": "graph", } ] } ] };

Aquí está mi intento:

 function buildTree(links) { const map = { } const findNodeInChildren = (name, obj) => { if (obj[name]) { return obj } else if (!obj.children) { return null } for (let i = 0; i < obj.children.length; i++) { const found = findNodeInChildren(name, obj.children[i]) if (found) return found } return null } links.forEach(link => { const foundNode = findNodeInChildren(link.parent, map) if (!foundNode) { const newNode = { name: link.parent, children: [] } map[newNode.name] = newNode } else { foundNode[link.parent].children.push({ name: link.children, children: [] }) } }) return map } const links = [ {parent: "flare", children: "analytics"} , {parent: "analytics", children: "cluster"} , {parent: "flare", children: "scale"} , {parent: "analytics", children: "graph"} , ]; const tree = buildTree(links) const json = JSON.stringify(tree) console.log(json)

Aquí está el JSON embellecido: no funciona según lo previsto:

 { "flare": { "name": "flare", "children": [ { "name": "scale", "children": [] } ] }, "analytics": { "name": "analytics", "children": [ { "name": "graph", "children": [] } ] } }

¿Qué está yendo mal?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Uno de los problemas en su código es cuando !foundNode es verdadero, entonces no agrega el (primer) elemento secundario a su matriz de elementos children .

En segundo lugar, el objeto que devuelve su código es el mapa en sí, obviamente con un objeto simple en el nivel superior con claves con nombre, en lugar de una matriz de objetos con claves de "nombre". El código debe convertir la estructura del mapa (que de hecho está anidada) en la estructura anidada deseada.

También es extraño que findNodeInChildren devuelva el map completo (es decir, obj ) cuando se encuentra el nodo. Tendría más sentido si se devolviera obj[name] , y el resto del código se adaptara a eso.

También puede condensar el código un poco más.

Así es como yo propondría hacerlo:

 const links = [ {parent: "flare", children: "analytics"} , {parent: "analytics", children: "cluster"} , {parent: "flare", children: "scale"} , {parent: "analytics", children: "graph"} , ]; // Create a Map keyed by parent, so that for each parent there is a // corresponding object, with (so far) empty children property. // This uses the argument that can be passed to the Map constructor: let map = new Map(links.map(({parent}) => [parent, { name: parent, children: [] }])); // Iterate the input again, and look up each parent-related object, // and insert there the child object, if found in the map, or otherwise // create an object for it without a children property (it has none). for (let {parent, children} of links) map.get(parent).children.push(map.get(children) ?? { name: children }); // Delete from the map all nodes that have a parent for (let {children} of links) map.delete(children); // What remains are the nodes at the top level (roots). Extract these // objects from the map and store them as array let result = [...map.values()]; console.log(result);

Este código devuelve una matriz , porque la estructura de entrada no garantiza que haya una sola raíz. Podría representar un bosque . Si está seguro de que es un árbol (es decir, con una raíz), puede sacar el elemento único de la matriz.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!