0

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.

10
  • 3
    You need to call $.parseJSON() to convert the string to an array. Commented Jul 3, 2014 at 21:35
  • 2
    After you fix that, you have another problem. At the end of the loop, comment will just contain the last element of the array. That element only has country, not fname, sname, or id. Commented Jul 3, 2014 at 21:37
  • It is data sent from the server side via ajax Commented Jul 3, 2014 at 21:39
  • 1
    Did you use dataType: 'json' in the AJAX call, so that it would be parsed automatically? Why are you showing it as a string if it has already been parsed? Commented Jul 3, 2014 at 21:40
  • 1
    Ok, your actual problem is that you're mangling the data on the server side with that. Instead you should probably do $user[0]['country'] = 'England';. Commented Jul 3, 2014 at 21:47

3 Answers 3

1
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"}]';
Sign up to request clarification or add additional context in comments.

3 Comments

It's not an array, it's a string.
I am assuming that he parses the string before iterating through it. I am aware that var foo = "a_string" is a string.
You're right. He says he gets a correct result for comment.country, so it must be parsed.
1

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.