在JSON对象中查找特定值

时间:2017-02-26 19:13:42

标签: javascript jquery json

{
  "adult": false,
  "budget": 17000000,
  "crew": [
    {
      "credit_id": {},
      "department": "Directing",
      "id": 40223,
      "job": "Director",
      "name": "Joe Carnahan",
      "profile_path": "/5YPrZ1JprLwtU4tn5DG0wqLjsAT.jpg"
    },
    {
      "credit_id": "55444d6bc3a368573b0008ba",
      "department": "Writing",
      "id": 40223,
      "job": "Writer",
      "name": "Joe Carnahan",
      "profile_path": "/5YPrZ1JprLwtU4tn5DG0wqLjsAT.jpg"
    },
    {
      "credit_id": "52fe4482c3a36847f809a3ed",
      "department": "Production",
      "id": 2236,
      "job": "Producer",
      "name": "Tim Bevan",
      "profile_path": "/f7o93O1KocuLwIrSa7KqyL1sWaT.jpg"
    }
}

嗨! 这是tmdb php api的tmdb示例输出。 例如,如何以jquery获取Director名称? 船员输出的顺序是随机的。

3 个答案:

答案 0 :(得分:0)

通常,当您在数组中搜索某些内容时,您希望迭代数组直到找到它。无论您使用的是jQuery还是纯JavaScript或任何其他具有数组的语言,都是一样的。

在您的情况下,您希望搜索属性job等于字符串"Director"的对象。

找到后,您希望从该对象返回属性name

您可以使用for循环执行此操作:

function findDirectorName(data) {
  for (let i = 0; i < data.crew.length; i++) {
    let crewMember = data.crew[i];
    if (crewMember.job === 'Director') {
      return crewMember.name;
    }
  }
}

或许是一个while循环:

function findDirectorName(data) {
  let i = 0;
  while (i < data.crew.length) {
    let crewMember = data.crew[i];
    if (crewMember.job === 'Director') {
      return crewMember.name;
    }
    i++;
  }
}

使用内置方法Array.prototype.find和箭头功能,您可以将代码简化为:

function findDirectorName(data) {
  let director = data.crew.find(crewMember => crewMember.job === 'Director');
  return director ? director.name : undefined;
}

答案 1 :(得分:0)

试试这个:

var aMovie = {
  "adult": false,
  "budget": 17000000,
  "crew": [
    {
      "credit_id": {},
      "department": "Directing",
      "id": 40223,
      "job": "Director",
      "name": "Joe Carnahan",
      "profile_path": "/5YPrZ1JprLwtU4tn5DG0wqLjsAT.jpg"
    },
    {
      "credit_id": "55444d6bc3a368573b0008ba",
      "department": "Writing",
      "id": 40223,
      "job": "Writer",
      "name": "Joe Carnahan",
      "profile_path": "/5YPrZ1JprLwtU4tn5DG0wqLjsAT.jpg"
    },
    {
      "credit_id": "52fe4482c3a36847f809a3ed",
      "department": "Production",
      "id": 2236,
      "job": "Producer",
      "name": "Tim Bevan",
      "profile_path": "/f7o93O1KocuLwIrSa7KqyL1sWaT.jpg"
    }]
};

var findDirector = function(aMovie){
  if( !aMovie.crew || aMovie.crew.length==0 ) return "";
  
  var director = aMovie.crew.find( function(member){
      return member.job.toLowerCase() == 'director';
  });
  return director.name;
};

alert(findDirector(aMovie));

答案 2 :(得分:0)

我喜欢使用 some()

aMovie.crew.some(function(member) {

    var job = member.job.toLowerCase();

    if(job == "director") return member;

}