Me gusta construir una lista de nombres para una matriz. Necesita encontrar el nombre de Level1 y luego pasar por la cadena hasta Level3 . Si no coincide con el Nivel 1, intente con el Nivel 2; si aún no coincide, intente obtener el Nombre del Nivel 3
Por ejemplo Salida:
getNames("Office") para devolver ["Office", "Microsoft", "Software"]
getNames("Apple") para devolver ["Apple", "Software"]
getNames("Tesla") para devolver ["Tesla", "Car"]
Datos
const data = { "Level1": [ { "Names": [ "Office" ], "Level": "Level2#Microsoft" } ], "Level2": [ { "Names": [ "Apple", "Microsoft" ], "Level": "Level3#Software" }, { "Names": [ "Tesla" ], "SubLevel": "Level3#Car" }], "Level3": [ { "Names": [ "Software" ] }, { "Names": [ "Car" ] } ] }Estoy luchando con la forma de llevar los datos al siguiente nivel sin escribir muchas condiciones.
Uso incompleto:
function getNames(name) { const namesBuild = []; const foundName = data.Level1.find(row => { return row.Names.find(rowName => rowName === name) }); if (foundName) { namesBuild.push(name); const subLevel = foundName.Level.split("#"); const catLevel = subLevel[0]; const catName = subLevel[1]; // How to continue to find next chain from object without many if conditions? } else { // attempt to find next level Level2, if not found then try Level3 } return namesBuild; }