-4

I need to return the object which hobbies is reading, below is my sample scenario

[
    {
        "id": 1,
        "name": "john",
        "hobbies": [
            {
                "id": 1,
                "name": "playing"
            }
        ]
    },
    {
        "id": 3,
        "name": "peter",
        "hobbies": [
            {
                "id": 3,
                "name": "reading"
            }
        ]
    }
]

// Expected Output:
[
    {
        "id": 3,
        "name": "peter",
        "hobbies": [
            {
                "id": 3,
                "name": "reading"
            }
        ]
    }
]

I use filter() and find() method however i couldn't loop it inside hobbies array

2 Answers2

1

Use Array#filter in conjunction with Array#some.

let arr = [ { "id": 1, "name": "john", "hobbies": [ { "id": 1, "name": "playing" } ] }, { "id": 2, "name": "mary", "hobbies": [ { "id": 2, "name": "cleaning" } ] }, { "id": 3, "name": "peter", "hobbies": [ { "id": 3, "name": "reading" } ] } ];
let res = arr.filter(x => x.hobbies.some(h => h.name === 'reading'));
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • 2
    You could have voted to close this question instead of answering a question which doesn't provides any relevant attempt to solve it. – Nitheesh Feb 10 '23 at 09:52
0

Use Array.prototype.filter method to filter the outer array and Array.prototype.some method to check if an object in the inner hobbies array has a name property of "reading"

let people = [ { "id": 1, "name": "john", "hobbies": [ { "id": 1, "name": "playing" } ] }, { "id": 2, "name": "mary", "hobbies": [ { "id": 2, "name": "cleaning" } ] }, { "id": 3, "name": "peter", "hobbies": [ { "id": 3, "name": "reading" } ] } ];

let readingPerson = people.filter(person => 
  person.hobbies.some(hobby => hobby.name === "reading")
)[0];

console.log(readingPerson);
NIKUNJ PATEL
  • 2,034
  • 1
  • 7
  • 22