Mike_Laird
Mike_Laird

Reputation: 1124

don't understand how to use jQuery $.each to iterate this JSON

I get JSON from my server and I want to set values of input boxes on a web page. The JSON pairs are the id and value of the inputs. The test JSON looks like

[{"city":"Rochester, Monroe County","country":"US","streetAddress":"12 Gibbs Street"}]

The real JSON will be much longer with more key value pairs in the one object.

When I use this hard coded statement, it sets the input value.

$('#city').val( responseParsed[0].city );  //this sets the city input to a value

I have tried to extend/automate that with $.each. I'm trying to learn to use it. I just can't get the hang of it. I'm feeling dense, at the moment, after many attempts. Here's the code for the success option in ajax.

success: function ( response ) {    
    if ( response ) {
        responseParsed = JSON.parse( response );
        $.each( responseParsed, function( key, value ){
            $('#key').val( responseParsed[0].key );
            console.log( $('#key').val( responseParsed[0].key ) + '|eachItem' ); // [object Object]|eachItem only once & input values do not change
        });
    }

Upvotes: 0

Views: 2558

Answers (2)

Hugo Tostes
Hugo Tostes

Reputation: 412

I think you want this:

success: function ( response ) {    
    if ( response ) {
        responseParsed = JSON.parse( response );
        $.each( responseParsed[0], function( key, value ){
            $('#' + key).val(value);
        });
    }

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227240

You don't need to use responseParsed inside your $.each. That's what the key and value parameters mean.

Your value (or this) is the current element of the array.

$.each(responseParsed, function(key, value){
    $('#city').val(value.city);
});

To get each key from the object, you'd need another $.each:

$.each(responseParsed, function(index, data){
    $.each(data, function(key, value){
        $('#'+key).val(value);
        console.log(key, value);
    });
});

Upvotes: 3

Related Questions