如何在 angular 中正确过滤数组

how to properly filter an array in angular

我有一个从后端拉取数组的服务冰,我需要根据 ID 从数组中获取单个项目,我如何在 Angular 中执行此操作?

I'm looking for how to do it specifically with angulars pipeable operators. Filter tends to just stop everything from working without throwing errors if not done correctly. I can get the the row info but I cant target the properties i get "Cannot read property 'id' of undefined"

I need to get a single item from the array based on the ID

试试 Array.find()

let data = yourArray.find(x => x.id == "en-gb");

或尝试 array().filter().shift()

请完成下面的讨论

 this.booksByStoreID = this.books.filter(
      book => book.store_id === this.store.id);

对于数组中的单个项目。

let selectedId = Array.find(a => a.id == 'fr-fr');

angulars pipeable operators

我不完全确定你所说的 angulars 管道运算符是什么意思。您的问题中有标签 rxjs-pipeable-operators,所以我希望您指的是一般的 rxjs 运算符。

所以我假设你实际上想做什么。如果我理解有误,请发表评论。

您有一项服务,其中 returns 来自数组的 Observable。像这样:

function getMyData(): Observable<any[]> {
    return Observable.create(observer => {
        observer.next([
            { name: 'value 1', id: 1 },
            { name: 'value 2', id: 2 },
            { name: 'value 3', id: 3 }
        ]);

    });
}

如果你想修改这个可观察流中的值,你不能直接在流上使用过滤器或查找。您收到的值是完整数组,因此查找操作是在数组对象上执行的,而不是单个项目。您要做的是映射结果值并在映射函数中对其进行过滤。

getMyData()
    .map((theArray: any[]) => theArray.find(item => item.id === 2))