-1

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"
 }
 ]
 }
]
asked Jul 3, 2016 at 4:56
3

3 Answers 3

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);
 });
}

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
Sign up to request clarification or add additional context in comments.

Comments

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;
});
answered Jul 3, 2016 at 5:00

1 Comment

You can use return hobbies.some instead.
0

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

1 Comment

Nice running example

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.