Home > Back-end >  How to map an Object with TypeScript - React
How to map an Object with TypeScript - React

Time:06-23

My goal is to list the categories names (prospecting and estimate in this case)

New with TypeScript, i'm trying to map this Object :

{
    "categories": {
        "prospecting": {
            "name": "Nos offres",
            "products": {
                "product1": {
                    "service": "Le pack",
                    "title": "Le pack",
                    "description": "Un accompagnement unique à 360° au service de votre performance.  erat nibh, tristique quis augue ac, egestas porttitor mauris-",
                    "redirect": "/accueil"
                },
                "product2": {
                    "service": "Nouveauté",
                    "title": "Le pack 2",
                    "description": "Vestibulum erat nibh, tristique quis augue ac, egestas porttitor mauris-",
                    "redirect": "/accueil"
                }
            }
        },
        "estimate": {
            "name": "Nos offres",
            "products": {
                "product1": {
                    "service": "Le pack",
                    "title": "Le pack",
                    "description": "Un accompagnement unique à 360° au service de votre performance.  erat nibh, tristique quis augue ac, egestas porttitor mauris-",
                    "redirect": "/accueil"
                },
                "product2": {
                    "service": "Nouveauté",
                    "title": "Le pack 2",
                    "description": "Vestibulum erat nibh, tristique quis augue ac, egestas porttitor mauris-",
                    "redirect": "/accueil"
                }
            }
        }
    }
}

Here is my attempt :

export default function Filters(props: any) {
    const [listOfCategories, setListOfCategories] = useState()

    useEffect(() => {
        const listOfCategories = props.categories.map(category => {
            setListOfCategories(category)
        })
        console.log(listOfCategories)
    })

but VSCode underline in red "category" map function and says : Parameter 'category' implicitly has an 'any' type

Anyone can help me to solve this ?

Thank you very much for your time

CodePudding user response:

if you are expecting an object without getting the data from api call it's enough to get it like this:

const [listOfCategories, setListOfCategories] = useState(
 Object.keys(props.categories)
);

Or inside useEffect like this :

useEffect(() => {
const categoriesList = Object.keys(props.categories);
setListOfCategories(categoriesList)
console.log(categoriesList)
}, [props.categories]);
  • Related