I am trying to return all objects that have a specific 'id' in the nested array. In the sample data, I'd like to return all person objects with hobbies id of 2 (hiking).
The other question addresses the problem of finding all values in an array based on an object value.
This question differs from the previous because I need to return all objects based on a value inside of a nested array.
[
{
"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"
}
]
}
]
-
Possible duplicate of How to access specific value from a nested array within an object array?Akshay Khandelwal– Akshay Khandelwal2016年07月03日 04:58:29 +00:00Commented Jul 3, 2016 at 4:58
-
3Haven't you already asked the same question here? stackoverflow.com/questions/38166623/…Akshay Khandelwal– Akshay Khandelwal2016年07月03日 04:58:57 +00:00Commented Jul 3, 2016 at 4:58
-
1Dear Jasmin, SO is not get code for free site. You have to share your efforts as well.Rajesh Dixit– Rajesh Dixit2016年07月03日 05:03:05 +00:00Commented Jul 3, 2016 at 5:03
3 Answers 3
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);
});
}
If you wanna use the new cool ES6 syntax:
function filterByHobby(people, hobbyId) {
return people.filter(
person => person.hobbies.some(
hobby => hobby.id === hobbyId
)
);
}
answered Jul 3, 2016 at 8:13
Mouad Debbar
3,2462 gold badges22 silver badges22 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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;
});
answered Jul 3, 2016 at 5:00
Piyush.kapoor
6,8311 gold badge25 silver badges21 bronze badges
1 Comment
Rajesh Dixit
You can use
return hobbies.some instead.Try this, I think its solve your proble:
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);
answered Jul 3, 2016 at 5:51
Govind Samrow
10.2k14 gold badges59 silver badges90 bronze badges
lang-js