Diamond
Diamond

Reputation: 608

Accessing array values show undefined

I have an array

var data = [{"fname":"john","sname":"doe","id":"2"},{"country":"England"}];

I tried iterating with this:

var comment='';

for(var i = 0; i < data.length; i++) {
    comment = data[i];

}

I access the data with this:

alert(comment.fname);
alert(comment.sname);
alert(comment.id);
alert(comment.country);

Only comment.country displays correctly, the rest show undefined.

Upvotes: 0

Views: 43

Answers (3)

Diamond
Diamond

Reputation: 608

Just got it;

I did not change the codes at the server side.

var comment=[];
$.each(data, function(key, val) {
    $.each(val, function(index, value){
            comment[index]=value;
    });
}); 

And all the values where displayed

alert(comment.fname);
alert(comment.sname);
alert(comment.id);
alert(comment.country);

Upvotes: 0

Barmar
Barmar

Reputation: 782499

Your loop is overwriting comment each time through the loop, so at the end it just contains the last element of data. If you want comment to contain properties from the other elements, you need to pick them up during the loop.

comment = {}
$.each(data, function(i, obj) {
    $.extend(comment, obj); // Merge the properties if each element into comment
});

Upvotes: 1

dekomote
dekomote

Reputation: 4027

var data ='[{"fname":"john","sname":"doe","id":"2"},{"country":"England"}]';

This array holds 2 different objects. If the same object has fname, sname, id and country, you should probably make them one.

var data ='[{"fname":"john","sname":"doe","id":"2","country":"England"}]';

Upvotes: 1

Related Questions