Filtering an array based object's property inside a method

Viewed 45

I have the following two simple objects:

clinics: [
    { 
        id: 1,
        name: 'New Hampshire Veterinarian Clinic',
        plans: [
            'handle123',
            'handle567',
        ]
    },
    {
        id: 2,
        name: 'Westminster Moltchester Clinic',
        plans: [
            'handle123',
            'handle789',
        ]
    }
],
animals: [
    { 
        id: 1,
        handle: 'handle123',
        name: 'Cat',
    },
    {
        id: 2,
        handle: 'handle567',
        name: 'Dog',
    },
    {
            id: 3,
            handle: 'haneld789',
            name: 'Horse'
    }
],

I have the following method:

updateAnimals(selectedOption, id) {
}

where selectedOption is one object from the clinics array.

I want to filter the second array so it only contains the handles mentioned in the selected option, but I'm having trouble with the arguments. I want to achieve something like this:

updateAnimals(selectedOption, id) {
    let filteredAnimals = this.animals.filter(function({id, handle, name}) {
       // Access the selectedOption here so I can use it to filter
    });
}

But I'm not sure how to access the selected option inside the function... Or is there a better way to do that?

2 Answers

You can use selectedOption just like any other variable available in a scope by simply using it directly selectedOption.something:

updateAnimals(selectedOption, id) {
    let filteredAnimals = this.animals.filter({ handle } => {
       return selectedOption.plans.includes(handle)
    });
}
updateAnimals(selectedOption, id) {
  const handles=selectedOption.plans;
  let result= animals.filter(animal=>handles.includes(animal.handle)); 
}
Related