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

javascript - Get json value dynamically - Stack Overflow

programmeradmin0浏览0评论
{
 "id":["123"],
 "optionid_123":"98"
}

I have the id as a variable, but from that how can I get the optionid_*? I tried a few things, but nothing seems to work. The each is inside of the appropriate function and jsonid contains the correct value. Here is my attempt at accessing the value 98 which doesn't work:

$.each(data.id,function(){
    var jsonid = this;
    console.log( data.optionid_+jsonid ); // doesn't work
});
{
 "id":["123"],
 "optionid_123":"98"
}

I have the id as a variable, but from that how can I get the optionid_*? I tried a few things, but nothing seems to work. The each is inside of the appropriate function and jsonid contains the correct value. Here is my attempt at accessing the value 98 which doesn't work:

$.each(data.id,function(){
    var jsonid = this;
    console.log( data.optionid_+jsonid ); // doesn't work
});
Share Improve this question edited Jun 12, 2012 at 1:05 Paul 142k28 gold badges284 silver badges271 bronze badges asked Jun 11, 2012 at 1:08 anotherdevanotherdev 1037 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

You can use Bracket notation:

console.log( data['optionid_' + jsonid] );

I think your loop with data.id is not correct. That is

$.each(data.id, function() {..})

is incorrect.

For example if you data looks like following:

var data = [{
 "id":["123"],
 "optionid_123":"98"
},
{
 "id":["456"],
 "optionid_456":"99"
}];

Then you need to loop over data and get your required property.

$.each(data, function(index, val) {
  var jsonid = val.id[0]; // as val.id is array so you need [0] to get the value
  console.log(val['optionid_' + jsonid]); // bracket notation used
});

DEMO

发布评论

评论列表(0)

  1. 暂无评论