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

158
Views
obtener id por valor en datos jerárquicos con js

Tengo datos jerárquicos como matriz de árbol:

 var myData = [ { id: 0, title:"Item 1" }, { id: 1, title:"Item 2", subs: [ { id: 10, title:"Item 2-1" }, { id: 11, title:"Item 2-2" }, { id: 12, title:"Item 2-3" } ] }, { id: 2, title:"Item 3" }, // more data here ];

Necesito obtener una identificación por título en esta matriz. Intento usar esta función:

 console.log(myData.findIndex(item=>item.title==="Item 3"))

Pero funciona mal para el "Artículo 2-2". ¿Cómo debo solucionar este problema?

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

0

Hice este simple método findId para encontrar el título y devuelve el id o undefined como resultado obtenido para la estructura de su matriz de datos.

Esto funcionará bien, suponiendo que cada título sea único en la matriz.
De lo contrario, solo se encontrará el primero.

Echa un vistazo a lo siguiente

 var myData = [{ id: 0, title: "Item 1" }, { id: 1, title: "Item 2", subs: [{ id: 10, title: "Item 2-1" }, { id: 11, title: "Item 2-2" }, { id: 12, title: "Item 2-3" }] }, { id: 2, title: "Item 3" }, // more data here ]; function findId(title) { // Item with the equal title or with a children with an equal title const item = myData.filter(d => (d.title === title || d?.subs?.filter(s => s.title === title).length > 0))[0]; if (item) { // Check if is the main element or is one of the subs (with ternary operator) const id = item.title === title ? item.id : item?.subs?.filter(s => s.title === title)[0].id; // Return the id return id; } // Return undefined if not found return undefined; } console.log("Id: ", findId("Item 3")); console.log("Id: ", findId("Item 2-3")); console.log("Id: ", findId("Item 2-1")); console.log("Id: ", findId("Not Found"));

El último devuelve undefined según lo previsto, ya que el título no está incluido en 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!