I am a beginner who just started writing in typescript.
I would like to ask how to map an array of objects with a children array efficiently.
what I am trying to do is I am trying to map navigation menu item objects to two arrays for a json LD object.
I have an array of navigation items as below.
const navigationMenuItems = (
{name:'TOP', path:'/', hasChildren:false},
{name:'commitment', path:'/commitment', hasChildren:false},
{name:'items', path:null, hasChildren:true,
children:(
{ name:'logo', path:'/logo', hasChildren:false },
{ name:'wappen', path:'/wappen', hasChildren:false },
)
},
);
I wanted to map the object’s fields to two arrays for a json LD object like this. The json LD object has the name field and the url field, and they take arrays.
{
"@context": "https://schema.org",
"@type": "SiteNavigationElement",
"name" :('TOP', 'commitment','items'),
"url":('https:/sample.com/','https:/sample.com/commitment')
}
my solution was to use forEach loops twice as below.
I made two arrays and pushed each field in each array. Quite simple..
export function generateWebPageJsonLd(navigationItems:Array<navigationItemType>) {
let names= ();
let paths = ();
return flatNavigationList(navigationItems,names,paths);
}
const flatNavigationList = (navigationItems: Array<navigationItemType>, names, paths) => {
const result = navigationItems.forEach(element => {
if (element.hasChildren === false) {
return names.push(element.name) && paths.push(`${process.env.NEXT_PUBLIC_SITE_URL}${element.path}`)
}
else {
return element.children.forEach(child => {
return names.push(child.name) && paths.push(`${process.env.NEXT_PUBLIC_SITE_URL}${child.path}`)
})
}
})
return result;
}
I wanted to use Map but I had to use flatMap twice so I went for Foreach.
This code does what I want, however, somehow I feel like this is not the cleanest and most efficient way to go about this.
Can someone please make suggestions as to how to make this solution better?
Thanks in advance.