Reputation: 5309
I have a JSON from Java that looks like this:
[{
"col_name_1": "Name",
"col_value_1": "Deepu",
"col_name_2": "Age",
"col_value_2": "22",
"col_name_3": "gender",
"col_value_3": "Male"
}]
Some times the number of content (key value pair) of JSON may increase or decrease. So I decided to retrieve the data using for loop
in jQuery. My code is:
var tabdata = $.parseJSON(data);
var ele_count = Object.keys(tabdata[0]).length;
ele_count = parseInt(ele_count) / 2; //total key-value pair
for (var j = 1; j <= parseInt(ele_count); j++) {
var cn = "col_name_" + j;
var cv = "col_value_" + j;
alert(tabdata[0].cn);
alert(tabdata[0].cv);
}
Both alerts give undefined
. But using
tabdata[0].col_name_1
or tabdata[0].col_value_1
etc gives the desired result. The problem is inside the for
loop. Can someone help me?
Upvotes: 1
Views: 64
Reputation: 2017
Here is working example: https://jsfiddle.net/y4x93mdq/
alert(tabdata[0][cn]);
alert(tabdata[0][cv]);
Upvotes: 1
Reputation: 337560
You need to use bracket notation when accessing the property of an object through a variable. Try this:
for (var j = 1; j <= parseInt(ele_count); j++) {
var cn = "col_name_" + j;
var cv = "col_value_" + j;
console.log(tabdata[0][cn]);
console.log(tabdata[0][cv]);
}
Upvotes: 1
Reputation: 32354
try the jquery each
function
var obj = [{"col_name_1":"Name","col_value_1":"Deepu","col_name_2":"Age","col_value_2":"22","col_name_3":"gender","col_value_3":"Male"}] ;
$.each(obj[0],function(i,v){
console.log(v);
});
Upvotes: 0
Reputation: 115222
In your code .cn
will try to get property cn
of the object which is undefined
. So instead use bracket notation to access object property with help of variable.
alert(tabdata[0][cn]);
alert(tabdata[0][cv]);
Upvotes: 2