Lukáš Unzeitig Lukáš Unzeitig - 2 months ago 7
Javascript Question

Go through object when keys are know

I have object

var routes = {
"home":{
hash: "/home",
children: {
"just-home": {
hash: "/home/just-home",
children: {...}
},
"sub-homea": {
hash: "/home/sub-homea",
children: {...}
}
},
"contact":{
hash: "/contact",
children: {
"just-contact": {
hash: "/contact/just-contact",
children: {...}
},
"sub-contact": {
hash: "/contact/sub-contact",
children: {...}
}
}
}


How i can set object to
just-contact.children
when i know for example - that first key is contact, and next just-contat.. ? I need to assign this object dynamically because the known keys will be all time different. So i need use any loop. something like this -

const pathArray = [contact,just-contact]
Object.keys(routes).map(function (item) {
if (routes[item] === pathArray[counter]){
ob = routes[item];
counter++;
}
})


but this will loop only once and it won't go to deep.

UPDATE for more clean explanation -

I will read from path location (localhost:3000/contact/just-contact) the values (contact,just-contact) , which i will save to array (
pathArray=[contact,just-contact]
), when the location path will be change, the keys in array will be change too. And i need to find children of last key, in this example children of
just-contact
key

Answer

Found simple solution -

pathArray.map(function (item) {
      if (obj[item].hash === item){
             obj = obj[item].children;
      }
})
Comments