如何根据嵌套数组中的值返回对象? (JavaScript)的

时间:2016-07-03 04:56:29

标签: javascript arrays json

我试图返回嵌套数组中具有特定“id”的所有对象。在示例数据中,我想返回业余爱好ID为2(徒步旅行)的所有人物。

另一个问题解决了根据对象值在数组中查找所有值的问题。

这个问题与前一个问题不同,因为我需要根据嵌套数组中的值返回所有对象。

[  
   {  
      "id":111222,
      "name":"Faye",
      "age":27,
      "hobbies":[  
         {  
            "id":2,
            "name":"hiking"
         },
         {  
            "id":3,
            "name":"eating"
         }
      ]
   },
   {  
      "id":223456789001,
      "name":"Bobby",
      "age":35,
      "hobbies":[  
         {  
            "id":2,
            "name":"hiking"
         },
         {  
            "id":4,
            "name":"online gaming"
         }
      ]
   }
]

3 个答案:

答案 0 :(得分:2)

function hasHobby(person, hobbyId) {
  return person.hobbies.some(function(hobby) {
    return hobby.id === hobbyId;
  });
}

function filterByHobby(people, hobbyId) {
  return people.filter(function(person) {
    return hasHobby(person, hobbyId);
  });
}

如果您想使用新酷的ES6语法:

function filterByHobby(people, hobbyId) {
  return people.filter(
    person => person.hobbies.some(
      hobby => hobby.id === hobbyId
    )
  );
}

答案 1 :(得分:0)

var arr = [  
   {  
      "id":111222,
      "name":"Faye",
      "age":27,
      "hobbies":[  
         {  
            "id":2,
            "name":"hiking"
         },
         {  
            "id":3,
            "name":"eating"
         }
      ]
   },
   {  
      "id":223456789001,
      "name":"Bobby",
      "age":35,
      "hobbies":[  
         {  
            "id":2,
            "name":"hiking"
         },
         {  
            "id":4,
            "name":"online gaming"
         }
      ]
   }
];

arr.filter(function(obj) {
 var hobbies = obj.hobbies;
 var x = hobbies.filter(function(hob) {
     if (hob.id == "2") return true;
});

if (x.length > 0) return true;
});

答案 2 :(得分:0)

试试这个,我认为它解决了你的问题:



var arr = [{
  "id": 111222,
  "name": "Faye",
  "age": 27,
  "hobbies": [{
    "id": 2,
    "name": "hiking"
  }, {
    "id": 3,
    "name": "eating"
  }]
}, {
  "id": 223456789001,
  "name": "Bobby",
  "age": 35,
  "hobbies": [{
    "id": 2,
    "name": "hiking"
  }, {
    "id": 4,
    "name": "online gaming"
  }]
}];
var x = arr.filter(function(el) {
  var rnel = el.hobbies.filter(function(nel) {
    return nel.id == 2;
  });
  return rnel.length > 0 ? true :false;
});
alert(x.length);