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?
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.