2014-10-01 73 views
1

我有2個陣列看起來像這樣:如何動態導航javascript多維數組數組?

vars arrayVars = ["s", "p", "o"] 

arrayBindings = [  { 
     "s": { "type": "uri" , "value": "http://ss.ldm.io/" } , 
     "p": { "type": "uri" , "value": "http://xmlns.com/foaf/0.1/name" } , 
     "o": { "type": "literal" , "value": "ss" } 
     } , 
     { 
     "s": { "type": "uri" , "value": "http://ss.ldm.io/" } , 
     "p": { "type": "uri" , "value": "http://xmlns.com/foaf/0.1/img" } , 
     "o": { "type": "uri" , "value": "http://fbcdn-sphotos-d-a.akamaihd.net/o.jpg" } 
     }, 
     ... 
     ] 

我想基礎上,第一個參數,基本上就能夠導航arrayBindings動態:

arrayBindings[0].s.value讓我"http://ss.ldm.io/"但這樣做它就像arrayBindings[0].arrayVars[0].value那樣沒有用。

回答

1

那是[]符號就派上用場了,其中:

arrayBindings[0][arrayVars[0]].value 

var arrayVars = ["s", "p", "o"] 
 

 
var arrayBindings = [  { 
 
     "s": { "type": "uri" , "value": "http://ss.ldm.io/" } , 
 
     "p": { "type": "uri" , "value": "http://xmlns.com/foaf/0.1/name" } , 
 
     "o": { "type": "literal" , "value": "ss" } 
 
     } , 
 
     { 
 
     "s": { "type": "uri" , "value": "http://ss.ldm.io/" } , 
 
     "p": { "type": "uri" , "value": "http://xmlns.com/foaf/0.1/img" } , 
 
     "o": { "type": "uri" , "value": "http://fbcdn-sphotos-d-a.akamaihd.net/o.jpg" } 
 
     }, 
 
] 
 
         
 
document.write(arrayBindings[0][arrayVars[0]].value);

+0

賓果!它的作品非常感謝。 – mzereba 2014-10-01 07:41:19

+0

不客氣。 – 2014-10-01 07:41:44

0

您可以通過使用brakets ([])dot (.)符號訪問對象屬性:

因此,arrayBindings[0].s.valuearrayBindings[0]['s']['value']返回相同的值http://ss.ldm.io/

Read this

現在,循環您的兩個數組,動態:

for (i = 0; i < arrayBindings.length; i++) { 
    for (j = 0; j < arrayVars.length; j++) { 
     document.write(arrayBindings[i][arrayVars[j]].value); 
    } 
}