Get JSON attribute value by paasing attribute name via "var" in Javascript - Stack Overflow

In json can we getattribute value by passing variably value . MeansIt works for mewhen "name&q

In json can we get attribute value by passing variably value . Means

It works for me when "name" attribute exists in my "returnData" json object

              // It works 
               var getColValue= returnedData[0].name

but it give undefined error

              // It Not works 
               var refVar ="name";
               var getColValue= returnedData[0].refVar;

In json can we get attribute value by passing variably value . Means

It works for me when "name" attribute exists in my "returnData" json object

              // It works 
               var getColValue= returnedData[0].name

but it give undefined error

              // It Not works 
               var refVar ="name";
               var getColValue= returnedData[0].refVar;
Share Improve this question edited Dec 15, 2012 at 7:30 user1905838 asked Dec 15, 2012 at 7:19 user1905838user1905838 111 silver badge3 bronze badges 1
  • 2 yeah, if returnedData doesn't have refVar property, you try to access it then you will receive "undefined" value. To make it work, you can try returnedData[refVar] jsfiddle/wsyCP/2 – secretlm Commented Dec 15, 2012 at 7:33
Add a ment  | 

2 Answers 2

Reset to default 2
var getColValue= returnedData[refVar];

should work. Please give it a try.

Use square bracket notation:

returnedData[refVar];

In other words, these two are basically equivalent:

returnedData["name"] === returnedData.name

Note that, using square-bracket notation allows you to set/get property names that wouldn't be valid with the dot notation. Eg, returnedData.some-prop is not a valid Javascript object, but returnedData["some-prop"] is.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745258933a4619119.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信