next2u next2u - 5 months ago 5
JSON Question

Retrieve json elements using for loop gives undefied in jquery

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?

Answer

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]);