JS Find an object in an array by one of its properties

73 Views Asked by At

Need to find an object by Sarah owner

const dogs = [
  { weight: 22, curFood: 250, owners: ['Alice', 'Bob'] },
  { weight: 8, curFood: 200, owners: ['Matilda'] },
  { weight: 13, curFood: 275, owners: ['Sarah', 'John'] }, //need to find this string by name 
  { weight: 32, curFood: 340, owners: ['Michael'] },
];

const findeOwner = dogs.find(acc => acc.owners === 'Sarah');  

just doesnt work If I remove the square brackets, then the method will work, but this is against the rules. Would you help me?

1

There are 1 best solutions below

0
XMehdi01 On

Use the find() method to find the object in the array that has "Sarah" as an owner using includes or indexOf.

const dog = dogs.find(dog => dog.owners.includes('Sarah')); //  dog.owners.indexOf('Sarah')>-1
console.log(dog);

Result:

{ weight: 13, curFood: 275, owners: ['Sarah', 'John'] }