first post!
I've done some searching around and found and tried some answers that were close to my problem, but none of them exactly matched.
I have an array of objects:
const kids = [
{ name: 'alice',
age: 13,
pets: [
{ type: 'fish', pet_name: 'nemo' },
{ type: 'cat', pet_name: 'snuffles'},
{ type: 'cat', pet_name: 'pixel'}
]
},
{ name: 'bob',
age: 7,
pets: [
{ type: 'dog', pet_name: 'rover' }
]
},
{ name: 'chris',
age: 15,
pets: [
{ type: 'cat', pet_name: 'fluffy' },
{ type: 'donkey', pet_name: 'eeyore' }
]
}
]
I want to get all the kids that own cats, using higher-order functions rather than loops. The result I want is
cat_owners = [
{ name: 'alice', age: 13,
pets: [ { type: 'cat', pet_name: 'snuffles' },
{ type: 'cat', pet_name: 'pixel' } ]
},
{ name: 'chris', age: 15,
pets: [ { type: 'cat', pet_name: 'fluffy' } ] }
]
i've tried various combinations of filter, forEach, find, such as
const cat_owners = kids.filter(kid => kid.pets.find(pet => pet.type === 'cat') )
const kids = [
{ name: 'alice',
age: 13,
pets: [
{ type: 'fish', pet_name: 'nemo' },
{ type: 'cat', pet_name: 'snuffles'},
{ type: 'cat', pet_name: 'pixel'}
]
},
{ name: 'bob',
age: 7,
pets: [
{ type: 'dog', pet_name: 'rover' }
]
},
{ name: 'chris',
age: 15,
pets: [
{ type: 'cat', pet_name: 'fluffy' },
{ type: 'donkey', pet_name: 'eeyore' }
]
}
];
const cat_owners = kids.filter(kid => kid.pets.find(pet => pet.type === 'cat'));
console.log(cat_owners);
But this also returns alice's fish and chris' donkey - i just want the cats. I've managed to confuse myself silly, and I just can't find the right invocation to get my catlovers and their cats, I've been struggling with this 'simple' problem for a couple of hours now...
so my question is "how do i achieve this desired result?"
thanks in advance
...
EDIT:
thanks to everyone that replied. i managed to do it with the help of the duplicate answer. I had to first filter the kids for pet_type == 'cat', then mapped each kid to a newKid if they had a cat, then filter by pet_type again:
const cat_owners = kids.filter(
kid => kid.pets.some(pet => pet.type === 'cat')
)
.map(kid => {
let newKid = Object.assign( {}, kid )
newKid.pets = newKid.pets.filter(pet => pet.type == 'cat')
return newKid
})
this code works, and I'm happy and much less confused.
i realise that there is more than one way to skin a cat, and i have not tried the suggested answers below.
thanks again