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

142
Views
Publicación asincrónica de objetos y relaciones padre-hijo (¿recursivamente?)

Digamos que estoy tratando de crear un "árbol genealógico" como una matriz JSON.

Así que tengo una matriz de objetos Person .

Cada objeto Person tiene un name obligatorio. Opcionalmente, cada objeto también puede tener un campo children que contenga una matriz de otros objetos Person (que también tienen un campo children , por lo que la "profundidad" del árbol genealógico puede continuar para siempre).

Si no hay hijos, el campo de los children será simplemente una matriz vacía [] .

P.ej

 const family_name = "The Numbers"; const family = [{ name: "1" children: [], }, { name: "2" children: [{ name: "2 - 1", children: [], }, { name: "2 - 2", children: [{ name: "2 - 2 - 1", children: [], }, ], } ], }, { name: "3" children: [{ name: "3 - 1", children: [], }, ], }, ]

Necesito PUBLICAR el "padre" antes que el "hijo". Cuando PUBLIQUE una Person , obtengo su id en el response.data . Esta id debe usarse en el POST del niño inmediato como parent_id para que el niño se asocie al padre.

También necesito PUBLICAR primero el "nombre de familia", que devolverá un family_id de familia. Este family_id se usará como parent_id solo para las Person más importantes.

p.ej

 axios.post(FAMILY_URL, {"family_name": family_name}) .then((response) => { // Promise.all() POST 1, 2, and 3 with their "parent_id" as response.data.family_id // Promise.all() POST 2-1 and 2-2 with their "parent_id" as 2's response.data.id // POST 2-2-1 with its "parent_id" as 2-1's response.data.id // POST 3-1 with its "parent_id" as 3's response.data.id })

Pero, ¿cómo se ve el código si se desconoce el número y la profundidad de los objetos Person ? Tengo que aprovechar una función recursiva, ¿verdad?

También me gustaría usar Promise.all() para todos los "hermanos"

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

0

Desea recorrer recursivamente la estructura de datos, acumulando promesas en el camino

 // fake axios, ignore this bit const FAMILY_URL="family-url",axios={post:async(a,o)=>(console.log(`POST ${a}`,o),{data:{id:`${a===FAMILY_URL?"":`${o.parent_id}-`}${Math.ceil(100*Math.random())}`}})}; // resolves an individual person by posting their details with a given // parent ID, then doing the same for any children const savePerson = async (parent_id, { name, children }) => { // get this person's ID const { data: { id } } = await axios.post("person-url", { name, parent_id }) return { id, // assign the ID for visibility name, // pass this person's ID as the children's parent children: await savePeople(id, children) } } // resolves an array of people given a "parent ID" const savePeople = (parent_id, people) => Promise.all(people.map(person => savePerson(parent_id, person))) // Top-level family helper const saveFamily = async (family_name, family) => { const { data: { id } } = await axios.post(FAMILY_URL, { family_name }) // resolve all the people in the family array return savePeople(id, family) } // minified const family = [{"name":"1","children":[]},{"name":"2","children":[{"name":"2 - 1","children":[]},{"name":"2 - 2","children":[{"name":"2 - 2 - 1","children":[]}]}]},{"name":"3","children":[{"name":"3 - 1","children":[]}]}] saveFamily("Smith", family).then(console.info)
 .as-console-wrapper { max-height: 100% !important; }

about 4 years ago · Juan Pablo Isaza Report

0

Lo abordaría usando el algoritmo BFS. Ejemplo:

 function postFamily(family) { const queue = []; queue.unshift(...family); while (queue.length) { const cur = queue.pop(); // HERE IS YOUR LOGIC RELATED TO THE CURRENT NODE // FOR EXAMPLE: axios.post('*FAMILY URL*', cur); for (const child of cur) { queue.unshift(child); } } }

No entiendo claramente el resultado deseado, pero me alegro si ayudaría. ¡Que tengas un lindo día!

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!