1

I am trying to display an array of key value pair, but couldn't code it properly.

 var result =new Array( {'id' : 1}, {'id' : 2} );

$.each($.parseJSON(result), function(k, v) {
    alert(k + ' is ' + v);
});

Here is the Fiddle links.

http://jsfiddle.net/27UFu/

1

3 Answers 3

2

I changed your code as below:

var result =[ {'id' : 1}, {'id' : 2} ];

$.each(result, function(k, v) {
    alert("id" + ' is ' + v.id);
});

According to your comments, here is the updated code:

var result =[ {'id' : 1}, {'id' : 2} ];

$.each(result, function(k, v) {
    for(var prop in v){
        if(v.hasOwnProperty(prop)){
            alert(prop + ' is ' + v[prop]);
        }
    }

});
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Alex, thank you for your code, But i need something different , Suppose if my array look like this means, how can i display the data. var result =[ {'first_id' : 1}, {'second_id' : 2} ]; here i need to show both things, first_id and its value 1. how to print those two items.
1

Try this.

var result =[ {'id' : 1}, {'id' : 2} ];

$.each(result, function(k, v) {
    for(var prop in v){
        alert(k + ' is ' + prop);
    }
});

Fiddle Demo

Comments

1
var result =new Array( {'id' : 1}, {'id' : 2} );
$.each(result, function(key, value){
    $.each(value, function(key, value){
        alert(key+' : '+value);
    });
});

1 Comment

Good answer, a explanation of what this code does would make it even better!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.