Deepu Sasidharan
Deepu Sasidharan

Reputation: 5309

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?

Upvotes: 1

Views: 64

Answers (5)

dpkrai96
dpkrai96

Reputation: 93

Use the following inside your for loop

tabdata[0][cn]

Upvotes: 0

Davor Mlinaric
Davor Mlinaric

Reputation: 2017

Here is working example: https://jsfiddle.net/y4x93mdq/

alert(tabdata[0][cn]);
alert(tabdata[0][cv]);

Upvotes: 1

Rory McCrossan
Rory McCrossan

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

madalinivascu
madalinivascu

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

demo

Upvotes: 0

Pranav C Balan
Pranav C Balan

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

Related Questions