Imagine having an array of dictionaries like the one below. How can I locate the object with id: 121
using JavaScript? I've been struggling to figure this out and would appreciate any hints or algorithms on how to achieve this.
The desired result should look something like
[{id:1, name:"foo"}, {id: 12, name:"shoo"}, {id: 121, name:"jhj"}]
[
{
"id": 1,
"name": "foo",
"submenus": [
{
"id": 11,
"name": "bar",
"submenus": [
{
"id": 111,
"name": "abc"
}
]
},
{
"id": 12,
"name": "shoo",
"submenus": [
{
"id": 121,
"name": "jhj"
}
]
}
]
},
{
"id": 2,
"name": "kjk"
}
]
This is the VueJS code snippet that I came up with:
getBreadcrumbs(menuItems, id, breadcrumbsArray) {
for (var i = 0; i < menuItems.length; i++) {
if (menuItems[i].id == id) {
breadcrumbsArray.push({
id: menuItems[i].id,
name: menuItems[i].text
})
return breadcrumbsArray
} else {
if (menuItems[i].submenus !== 'undefined') {
if (menuItems[i].submenus.length > 0) {
console.log('shoo')
this.getBreadcrumbs(menuItems[i].submenus, id, breadcrumbsArray)
}
}
}
}
}
When running this code, it throws the following error:
Error in render: "TypeError: menuItems[i].submenus is undefined"