2016-09-23 80 views
-2

我有对象去当按键知道

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: {...} 
    } 
    } 
} 

如何设置对象just-contact.children当我知道 - 例如,首先关键是接触,而旁边刚刚contat ..?我需要动态地分配这个对象,因为已知的键将会有所不同。所以我需要使用任何循环。像这样 -

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

但这只会循环一次,它不会深入。

UPDATE更多清洁解释 -
我将从路径位置读取(本地主机:3000 /接触/刚刚接触)的值(接触,只是接触),我将保存到阵列(pathArray=[contact,just-contact]) ,当位置路径将改变时,数组中的键也会改变。我需要找到最后一个键的孩子,在这个例子中的just-contact儿童关键

+2

这个问题不清楚。你说密钥是已知的*(“我知道第一个密钥是联系...”)*,但是你也说密钥是未知的*(“已知的密钥将全部不同”*)。这是什么? [mcve]会有所帮助。 –

+1

请尝试更好地解释问题,这是很难纠正你的答案。 – Wallkan

+0

什么是困难?我只需要在对象内部找到对象,当我知道键时(路径) –

回答

0

找到简单的解决方案 -

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