Spring
Spring

Reputation: 11835

how to browse a javascript object

I'm new to jQuery. Following is the data variable that contains a json dictionary.

{
   "user":null, 
   "currency":"EUR",
   "balance":0,
   "translist": [ 
       { "trans1":"something","trans2":"something2" }
   ]
}

and my jQuery method receives a json/Javascript object from the Rest GET call

success: function (data){    
        for(x in data) {
            console.log(x + ':   ' + data[x]);
        }       
    });

Is there any library that can help to parse/walk through this json object and get to some kind of objects list? I want to check some of the keys and their respective values. Problem is I don't need all the keys and values from the list and also some of the values can be null, which prevented me to apply some solutions I found using SO.

Or usually is it more common to directly start printing the HTML inside the success function?

EDIT:If it was java for example it would be a Map and I would use an iterator to walk through and see/analyse the map values, and create some array list with the values I want from it. What's equivalent of that in jQuery?

Upvotes: 1

Views: 692

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382170

If it was java for example it would be a Map and I would use an iterator to walk through and see/analyse the map values, and create some arraylist with the values I want in it. What is the equivalent of that in jQuery?

Any javascript object can be seen as an associative map.

You can for example directly access the currency as data['currency'].

You can also build an array :

var a = [];
for (var key in data) {
    a.push({key:key, value:data[key]});
}

You could also build some HTML and apply functions to the data :

$(document.body).append($(
   '<table>' + a.map(function(v){
      return '<tr><td>'+v.key+'</td><td>'+v.value+'</td></tr>'
   }).join('')+'</table>'
));

Demonstration

Using jQuery can make the same iteration simpler (working directly from data) :

$(document.body).append($(
   '<table>' + $.map(data, function(value,key){
      return '<tr><td>'+key+'</td><td>'+value+'</td></tr>'
   }).join('')+'</table>'
));

Demonstration

Upvotes: 3

palaѕн
palaѕн

Reputation: 73916

Try using each

success: function (data){   
    $.each( data, function( key, value ) {
        if(key === "currency")
            alert( key + ": " + value );
    });   
});

Upvotes: 1

Related Questions