基于嵌套数组中的匹配键值获取对象

时间:2013-12-13 01:19:12

标签: javascript json api jsonp

我有一个电影供稿,我正在尝试检索具有特定键值的对象的“名称”值。这是回复:

{
    genres: [
        {
            id: 18,
            name: "Drama"
        },
    ],
    homepage: "http://www.therewillbeblood.com/",
    id: 7345,
    imdb_id: "tt0469494",
    release_date: "2007-12-26",
    crew: [
        {
            id: 4762,
            name: "Paul Thomas Anderson",
            department: "Writing",
            job: "Screenplay",
            profile_path: "/6lDE5N6lQUvAbKBRazn2Q0mRk44.jpg"
        },
        {
            id: 52563,
            name: "Upton Sinclair",
            department: "Writing",
            job: "Novel",
            profile_path: null
        },
        {
            id: 2950,
            name: "Robert Elswit",
            department: "Camera",
            job: "Director of Photography",
            profile_path: null
        },
        {
            id: 1809,
            name: "Dylan Tichenor",
            department: "Editing",
            job: "Editor",
            profile_path: null
        },
        {
            id: 4762,
            name: "Paul Thomas Anderson",
            department: "Directing",
            job: "Director",
            profile_path: "/6lDE5N6lQUvAbKBRazn2Q0mRk44.jpg"
        },
        {
            id: 4772,
            name: "Cassandra Kulukundis",
            department: "Production",
            job: "Casting",
            profile_path: null
        }
    ]
}

所以我试图用“导演”的“工作”键值获得该对象,这将是Paul Thomas Anderson。

这是我的javascript,我根据release_date的值设置年变量。试着找出如何设置导演变量:

<script type="text/javascript">
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/movie/';

imdb_id = 'tt0102685';
key = '?api_key=XXXXXXXXXXXX';
append = '&append_to_response=credits';
$.ajax({
    type: 'GET',
    url: url + imdb_id + key + append,
    dataType: 'jsonp',
    success: function(data) {
      var $year = data.release_date.substring(0, 4);
      $('#year').html($year);
    },
});

});
</script>

任何帮助将不胜感激!花了将近两天的时间试图弄明白无济于事。

2 个答案:

答案 0 :(得分:3)

如果您使用的是现代浏览器,则可以使用filter功能:

var name = data.crew.filter(function(e){
    return (e.job=="Director") ? true:false;
})[0].name;

JS小提琴: http://jsfiddle.net/gTzyT/

错误处理示例

function getDirectorName(crew){
    var name = "";
    try{
        name = json.crew.filter(function(e){
           return e.job=="Director"
        })[0].name;
    }catch(err){
       name = "No Director";
    }
    return name;    
}

//calling the method                           
alert(getDirectorName(data.crew));

答案 1 :(得分:0)

对于稍微“不同”的方法,首先按作业排序。 E.g。

data.crew.sort(function(a,b) {
  return a.job == 'Director' ? -1 : 1;
});
console.log(data.crew[0].name); // => name of Director

jsfiddle here

注意:我不一定赞同这个解决方案。排序不是最高效的方法。它有副作用(改变data.crew数组的顺序,这可能是不可取的)。但这是一种“可爱”的解决方案,所以我想我会把它丢在那里。 :)