Filtering to specific nodes in JSON - use grep or map?

本秂侑毒 提交于 2019-12-24 20:14:03

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!