28 lines
883 B
TypeScript
28 lines
883 B
TypeScript
import { Categories, Category } from 'types/category'
|
|
import categoriesData from './../assets/categories/categories.json'
|
|
|
|
const flattenCategories = (
|
|
categories: (Category | string)[],
|
|
parentPath: string[] = []
|
|
): Categories[] => {
|
|
return categories.flatMap<Categories, Category | string>((cat) => {
|
|
if (typeof cat === 'string') {
|
|
const path = [...parentPath, cat]
|
|
const hierarchy = path.join(' > ')
|
|
return [{ name: cat, hierarchy, l: path }]
|
|
} else {
|
|
const path = [...parentPath, cat.name]
|
|
const hierarchy = path.join(' > ')
|
|
if (cat.sub) {
|
|
const obj: Categories = { name: cat.name, hierarchy, l: path }
|
|
return [obj].concat(flattenCategories(cat.sub, path))
|
|
}
|
|
return [{ name: cat.name, hierarchy, l: path }]
|
|
}
|
|
})
|
|
}
|
|
|
|
export const getCategories = () => {
|
|
return flattenCategories(categoriesData)
|
|
}
|