Skip to content
Advertisement

Need help creating a dynamic navigation menu

I’m creating an app for wireframing apps. I’m working on a function for generating links from the data of the wireframed app which will consist on an unpredictable amount of sections within sections. The interface for the sections are shaped like this

export interface ProjectObject{
    title: string;
    link?: string;
    summary?: string;
    description?: DescriptionPoint[];
    sections?: ProjectObject[];
    elements?: ProjectElement[];
    challenges?: ProjectChallenges[];
    feedback?: ProjectFeedbackItem[];
}

What I want to do is extract the title and link properties from each object and store it in a variable shaped like this

export interface NavLink{
    title: string;
    link: string;
    subLinks?: NavLink[]
}

The title and link properties are of course the properties to be extracted from each object. The subLinks property is for saving nested links to be retrieved from the additional sections in the sections property.

I came up with the following function in an attempt to extract and form the links

createProjectLinks(data: ProjectObject[]){
    return data.map(a=>{
        let links: NavLink = {
            title: a.title,
            link: a.link,
            subLinks: this.createProjectLinks(a.sections)};
        return links;
    });
}

When passing an array of ProjectObjects into it I get the following error

ERROR TypeError: Cannot read property ‘map’ of undefined

at first I thought it was an async issue but I created a const directly above the component to serve as dummy data to avoid asyncrounous problems and I’m still getting the same error passing the dummy data into the function. What am I doing wrong? Is there a better way for me to achieve this functionality?

Advertisement

Answer

The below error is not a typescript issue, but a javascript issue

TypeError: Cannot read property 'map' of undefined

do this

createProjectLinks(data: ProjectObject[] = []){ //give default value of [] to prevent mapping on undefined data
    return data.map(a=>{
        let links: NavLink = {
            title: a.title,
            link: a.link,
            subLinks: this.createProjectLinks(a.sections)};
        return links;
    });
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement