Necesito encontrar el último nivel de la categoría y escribirlo.
Ejemplo de cómo json puedo obtener:
{ category : 'One' , title : 'One category' , value : 1 }, { subcategory : 'Two' , title : 'Two category' , value : 2 }, { sub-subcategory : 'Three' , title : 'Three category' , value : 3 },Cada vez que tengo este ejemplo:
{ category : 'One' , title : 'One category' , value : 1 }, { subcategory : 'Two' , title : 'Two category' , value : 2 }Cada vez que tengo json con una sola categoría:
{ category : 'One' , title : 'One category' , value : 1 },Lo que necesito ? Necesito encontrar la categoría del último nivel si elijo solo la categoría, necesito encontrar solo el valor de la categoría. Si elijo la categoría y la subcategoría, necesito encontrar el valor de la subcategoría ... Si tengo json con categoría, subcategoría y subsubcategoría, necesito filtrar y obtener valores del último -> valor de subsubcategoría.
estoy probando con:
categories.map(categoryLevel => categoryLevel?.value);pero esto no es propiedad del trabajo.
esto también es extraño porque no puedo ponerlo todo en 1 json. que me vienen con iones especiales... Ejemplo
{ category : 'One' , title : 'One category' , value : 1 }, { subcategory : 'Two' , title : 'Two category' , value : 2 }, { sub-subcategory : 'Three' , title : 'Three category' , value : 3 },Estos son tres json diferentes... Nadie...
Si sabe que solo hay esas 3 posibilidades, puede contar.
if (categories.length === 3) { // you know there's sub-subcategory, find that } else if (categories.length === 2) { // you know there's subcategory, find that } else { // find the category }De lo contrario, puede intentar encontrar el nivel más alto y, si no lo encuentra, moverse hacia abajo.
let highest = null; highest = categories.find(c => c['sub-subcategory']); if (!highest) { // try to find subcategory } if (!highest) { try to find category }BESO
Si puede agregarlos a una matriz y el último nivel es la clave más larga, entonces
const cats = [{ "category" : 'One' , title : 'One category' , value : 1 }, { "subcategory" : 'Two' , title : 'Two category' , value : 2 }, { "sub-subcategory" : 'Three' , title : 'Three category' , value : 3 }] const levels = cats .reduce((acc,cur) => { acc.push(Object.keys(cur) .find(key => key.toLowerCase().endsWith('category'))); return acc},[]) .sort((a, b) => a.length - b.length) console.log(levels.pop())