2016-04-27 99 views
0

我具有其中我被號碼存儲公共汽車路線,然後通過名稱下列對象數組:如何在JavaScript中動態獲取對象的屬性值?

var routearray =[ 
ruta01 = 
    { 
     via01: "Progress", 
     via02: "Ten", 
     via03: "S", 
     via04: "Maria" 
    }, 
ruta02 = 
    { 
     via01: "Exterior", 
     via02: "Interior" 
    }, 
ruta03 = 
    { 
     via01: "University", 
     via02: "Henry St" 
    },]; 

我必須跟我要訪問的每個屬性的值以下代碼:

for(i=0;i<routearray.length;i++) //iterates through the array's objects 
    { 
     var props = Object.keys(routearray[i]); //array that stores the object properties 
     for(j=0;j<props.length;j++) //iterates through specific object properties 
     { 
      console.log(props[j]); //shows the property names 
      var propertystring = String(props[j]); //transforms the property name into string 
      console.log(routearray[i].propertystring]; //should access the property value 
     } 

    } 

當代碼的最後一行執行時,控制檯中會顯示8個「未定義」結果。如果我將其更改爲類似:

console.log(routearray[i].via01]; 

它工作得很好,但我不知道爲什麼,如果該字符串應該正常工作未訪問的價值。 我在做什麼錯?有沒有更好的辦法?

+0

您不需要將數組元素的屬性名稱轉換爲字符串;他們已經是字符串。你正在尋找'[]'運算符:將包含屬性名稱的變量的名稱放在括號中,就像你在括號中放置'i'來做數組索引一樣。這完全一樣。 – Pointy

+0

我曾想過,但有時候人們往往會想到複雜的方式。謝謝。 –

回答

1

它應該是:

console.log(routearray [i] [propertystring]);

通常,當您執行「someObject.key」時,實際值「key」必須作爲「someObject」中的一個屬性存在。但是,如果您執行「someObject [key]」,則變量「key」中包含的值必須作爲「someObject」中的一個屬性存在。

+0

太棒了!謝謝,非常感謝,有點顯而易見,但有時我們試圖尋找最複雜的解決方案。 –