{
"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
});
Paul
142k28 gold badges285 silver badges272 bronze badges
2 Answers 2
You can use Bracket notation:
console.log( data['optionid_' + jsonid] );
answered Jun 11, 2012 at 1:10
Paul
142k28 gold badges285 silver badges272 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
anotherdev
Ah ha! I tried a few bracket notations but for some reason was a little off. Cheers.
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
});
Paul
142k28 gold badges285 silver badges272 bronze badges
answered Jun 11, 2012 at 2:30
thecodeparadox
87.2k22 gold badges143 silver badges164 bronze badges
Comments
lang-js