最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论