问题
I'm using the themoviedb.org's API to retrieve information about films. It's returning this JSON data.
I need to filter this in two different ways, but not necessarily in the same callback. In one instance I only need to return the genres, and in another instance I need to return only the "backdrops" where size.toLowerCase() == 'original'
, and both instances take place in a success
for an ajax call, i.e.:
$.ajax({
url: "http://api.themoviedb.org/2.1/Movie.getInfo/en/json/API_KEY/" + filmID,
dataType: "jsonp",
context: document.body,
success: function(data){
...
}
});
Would grep or map be the proper method to use here? Regardless, how can I efficiently retrieve this info?
回答1:
you would use grep for filtering out the right things you wanted and placing them in another array, map would be to add further things to the JSON by performing a specific function on each element
var results = array();
$.ajax({
url: "http://api.themoviedb.org/2.1/Movie.getInfo/en/json/API_KEY/" + filmID,
dataType: "jsonp",
context: document.body,
success: function(data){
data = eval(data);
results = $.grep(data, function(data) {
return data[0].posters.image.size == "original";
});
}
});
回答2:
Sounds like a job for $.map
-- if you only need to return the genres, $.map
will let you build an array of just those pieces of the object, while $.grep
will build an array of complete movie objects.
来源:https://stackoverflow.com/questions/7690168/filtering-to-specific-nodes-in-json-use-grep-or-map