I need to find the last level of the category and write it.
Example how I json can got:
{ category : 'One' , title : 'One category' , value : 1 },
{ subcategory : 'Two' , title : 'Two category' , value : 2 },
{ sub-subcategory : 'Three' , title : 'Three category' , value : 3 },
Any time i got this example:
{ category : 'One' , title : 'One category' , value : 1 },
{ subcategory : 'Two' , title : 'Two category' , value : 2 }
Any time i got json with only one category:
{ category : 'One' , title : 'One category' , value : 1 },
What I need ? I need to find last level category if choice just category i need to find just category value. If choice category and subcategory I need to find subcategory value.... If got json with category , subcategory and sub-subcategory i need to filter and get values from last -> sub-subcategory value.
I am try with:
categories.map(categoryLevel => categoryLevel?.value);
but this is no work property.
this is also weird because i can't put it all in 1 json. than they come to me with special ions ... Example
{ category : 'One' , title : 'One category' , value : 1 },
{ subcategory : 'Two' , title : 'Two category' , value : 2 },
{ sub-subcategory : 'Three' , title : 'Three category' , value : 3 },
This is three different json... No one...
If you know there's only those 3 posibilities, you can count.`
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
}
Otherwise you can just try to find the highest level and if that's not found move lower.
let highest = null;
highest = categories.find(c => c['sub-subcategory']);
if (!highest) {
// try to find subcategory
}
if (!highest) {
try to find category
}
KISS
If you can add them to an array and the last level is the longest key, then
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())