2014-11-25 75 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 
      } 

     } 

它是更多的代码,但是你当你有在对象本身并没有直接的控制来处理这些问题,更是这样。

相关问题