【问题标题】:Filtering an array based object's property inside a method在方法中过滤基于数组的对象的属性
【发布时间】:2021-03-12 10:37:38
【问题描述】:

我有以下两个简单的对象:

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'
    }
],

我有以下方法:

updateAnimals(selectedOption, id) {
}

其中selectedOptionclinics 数组中的一个对象。

我想过滤第二个数组,使其仅包含所选选项中提到的句柄,但我遇到了参数问题。我想实现这样的目标:

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

但我不确定如何访问函数内的选定选项... 或者有更好的方法吗?

【问题讨论】:

    标签: javascript vue.js vuejs3


    【解决方案1】:

    您可以像使用作用域中的任何其他变量一样使用 selectedOption,只需直接使用它即可selectedOption.something

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

    【讨论】:

    • 哇......我的问题是我在过滤器之前将 selectedOption.handle 附加到另一个变量......或者至少我是这么认为的,只是正常访问它是如此简单。谢谢! :)
    【解决方案2】:
    updateAnimals(selectedOption, id) {
      const handles=selectedOption.plans;
      let result= animals.filter(animal=>handles.includes(animal.handle)); 
    }
    

    【讨论】:

    • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请编辑您的答案以添加一些解释,包括您所做的假设。
    猜你喜欢
    • 1970-01-01
    • 2021-03-13
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 2017-11-22
    • 2019-10-14
    相关资源
    最近更新 更多