【问题标题】:Angularfire2 - Sorting objects based on one of it's values?Angularfire2 - 根据其中一个值对对象进行排序?
【发布时间】:2017-04-06 13:31:31
【问题描述】:

我正在尝试根据每个对象的日期值对每个对象进行排序并获取每个唯一日期。

假设我们在 Firebase 的列表下有很多这样的对象:

{
    object123: {
        date: "11-12-2016", 
        title: "These nuts"
    }
}

在部分视图中我有这样的东西:

<div *ngFor="let date of uniqueDates">
  <h1>{{date}}</h1>
</div>

为了获取每个唯一日期,我创建了一个数组 uniqueDates,它应该包含每个唯一日期。

为了实现这一点,我尝试这样做:

 /* This was supposed to add each date value from all the objects to uniqueDates, 
 ** but did not work.
 ** "items" is a FirebaseListObservable
 */
 this.items.forEach(
   item => {item.subscribe(item => this.uniqueDates.push(item.date))}
 );

 /*This makes each value unique*/
 this.uniqueDates= Array.from(new Set(uniqueDates));

要获取与日期对应的每个对象,我继续这样:

<div *ngFor="let date of uniqueDates">
  <h1>{{date}}</h1>

  <div *ngFor="let item of items | async"> //Items is a FirebaseListObservable containing all the objects
    <div *ngIf="item.date is equal to date">
      <p>{{item.someData}}<p>
    <div>
  </div>
</div>

我应该采用这种方法吗?如果是这样,我如何以正确的方式将每个唯一日期推送到数组中?您将如何处理?

【问题讨论】:

    标签: arrays angular firebase firebase-realtime-database angularfire2


    【解决方案1】:

    你可以试试这个:

    let flags:any = [];
    let arrLength = this.items.length;
    this.uniqueDates = [];
    
    for(let count=0; i<arrLength; count++) {
      if(flags[this.items[count].date]) continue;
      flags[this.items[count].date] = true;
      this.uniqueDates.push(this.items[count]);
    }
    

    现在绑定 uniqueDates 数组来查看。希望这对你有用。

    【讨论】:

    • 谢谢。在这个算法之后做了一些修改,我让它完美地工作了。
    猜你喜欢
    • 1970-01-01
    • 2010-11-16
    • 2013-11-25
    • 1970-01-01
    • 2013-10-22
    • 2012-09-14
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    相关资源
    最近更新 更多