用其他数组过滤数组的最优雅的方式

时间:2022-10-22 00:18:36

I'm basically creating a getItemsByIds(ids) function where items is an array of objects, each having an id key, and ids an array of ids.

我基本上是在创建一个getItemsByIds(ids)函数,其中项目是一个对象数组,每个对象都有一个id键,id是一个id数组。

I'm newish to ES6 so I'm sure there's a more elegant way to solve this, and since all my services will have this type of function I'd like it to be as optimal as possible. Here's what I have now:

我对ES6很不满意,所以我确信有一种更优雅的方法来解决这个问题,因为我的所有服务都有这样的功能,所以我希望它尽可能的优化。以下是我现在所拥有的:

getItemsByIds (ids) {
    return this.getAllItems().then(items => items.filter(item => {
        for (var i = 0; i < ids.length; i++) {
            if (item.id == ids[i]) {
                return true;
            }
        }

        return false;
    }));
}

And like I said, the items array is basically this:

就像我说的,项目数组基本上是这样的:

[{id: 0, name: 'Foo'}, {id: 1, name: 'Bar'}, {id: 2, name: 'Baz'}]

2 个解决方案

#1


2  

You could turn it into ids.indexOf(item.id) > -1.

您可以将它转换为id . indexof (item.id) > -1。

getItemsByIds (ids) {
    return this.getAllItems()
    .then(items => items.filter(item => ids.indexOf(item.id) > -1));
}

#2


2  

An alternative to Array#indexOf, if available to you (e.g. polyfilled), is the ES2016 method Array#includes.

如果您可以使用数组#indexOf(如polyfilled),则是ES2016方法数组#include。

getItemsByIds (ids) {
    return this.getAllItems()
        .then(items => items.filter(item => ids.includes(item.id));
}

#1


2  

You could turn it into ids.indexOf(item.id) > -1.

您可以将它转换为id . indexof (item.id) > -1。

getItemsByIds (ids) {
    return this.getAllItems()
    .then(items => items.filter(item => ids.indexOf(item.id) > -1));
}

#2


2  

An alternative to Array#indexOf, if available to you (e.g. polyfilled), is the ES2016 method Array#includes.

如果您可以使用数组#indexOf(如polyfilled),则是ES2016方法数组#include。

getItemsByIds (ids) {
    return this.getAllItems()
        .then(items => items.filter(item => ids.includes(item.id));
}