首页 > 解决方案 > 根据 Object 值对 Observable 数组进行排序

问题描述

我正在从 firestore 返回一个 Observable 数组,并希望按我在数据库对象中创建的索引对它们进行排序。

它们存储在数据库中,如下所示:

在此处输入图像描述

然后它们根据键 ID(按字母顺序)在 UI 中显示,但是,我希望它们根据索引在 UI 中排序。但是,我确实需要将 id 作为初始键。

我已经尝试映射值并使用 sort() 来按下面 ode 中显示的索引排序,但仍然以随机顺序返回。

这就是我使用 map 尝试按索引的键值排序的方式。

this.bedrooms$ = this.property$.pipe(
     flatMap((property: any) => this._property.getAllBedrooms(property.bedrooms, this.propertyId))
   );


   this.sortedBedroom$ = this.bedrooms$.pipe(
     map((room: any) => {
      return room.sort((a: any, b: any) =>
          b.index - a.index
       );
     }
     )
   );

标签: javascriptarraysangularrxjsgoogle-cloud-firestore

解决方案


您的问题可能与此行有关,b.test - a.index而不是b.index - a.index.

AngularFirestore我会为此建议另一种解决方案,使用from获取从 firestore 中排序的数据@angular/fire

this.afs.collection<Bedroom>('bedrooms', ref => ref.orderBy('index'))

推荐阅读