2014-11-25 70 views
0

我想要一個抽象方法根據屬性名作爲參數傳遞給方法來讀取json對象的屬性。在jQuery中獲取傳遞給方法的屬性值

我覺得比較容易解釋一個例子。

假設我有以下的JSON對象:

var coll = 
[ 
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"}, 
    {"firstName":"Peter", "lastName":"Jones"} 
] 

function GetPropertyValue(collection, index, property_name) 
{ 
    : 
    : 
} 

其中

GetPropertyValue(coll, 0, 'firstName'); 

返回 「約翰」,而

GetPropertyValue(coll, 0, 'lastName'); 

返回「李四,並

GetPropertyValue(coll, 2, 'lastName'); 

返回 「瓊斯

問候。

回答

1

很簡單。你擁有一切。只需使用括號表示法進行組裝即可。順便說一下,我已經使得'G'很小,以符合JavaScript廣泛接受的命名約定。

function getPropertyValue(collection, index, property_name) { 
    return collection[index][property_name]; 
} 
+0

'property_name'是一個「字符串」,不能在對象前面,因爲它是一個特定的現有屬性。我錯了嗎? – user3021830 2014-11-25 14:54:26

+0

@ user3021830啊!對不起..檢查我的編輯出 – 2014-11-25 14:55:44

+0

這是完美的。非常感謝你。 – user3021830 2014-11-25 15:06:39

1

我會擴展Amit Joki的答案,包括一些檢查,以確保查詢甚至可以返回。事情是這樣的,也許:

function getPropertyValue(collection, index, property_name) { 
      if(collection[index].hasOwnProperty(property_name)){ 
       return collection[index][property_name]; 
      }else{ 
       //do something here id the property is not there 
      } 

     } 

它是更多的代碼,但是你當你有在對象本身並沒有直接的控制來處理這些問題,更是這樣。

相關問題