【问题标题】:ES6 / Typescript: Stacking map and filter advanced array methodsES6 / Typescript:堆叠映射和过滤高级数组方法
【发布时间】:2018-07-26 07:14:48
【问题描述】:

我在 Ionic / Angular 中有以下接口(为了清晰起见减去细节),这就是我使用 Typescript / ES6 的原因:

export interface Item {
  statusOfItem: string;
}
export interface checkin {
  items: Array<Item>;
}
export interface table {
  checkins: Array<Checkin>;
}

我需要编写一个函数,传入表对象,但表中的签入都被它们的状态过滤。

这是我想出的功能:

transformTable(table: Table, status: string): Table{
  let newTable: Table = table;
  newTable.checkins = table.checkins.map(
    checkin => {
      let newCheckin: Checkin = checkin;
      newCheckin.items = checkin.items.filter(
        item => item.statusOfItem == status
      );
      return newCheckin;
    }
  )
  return newTable;
}

我想使用新的数组函数,如 map 等。这可以更有效地完成/编写(例如,没有let)。

【问题讨论】:

  • 新的数组函数? Firefox 自 2005 年以来就拥有它们。
  • 请注意,赋值(或初始化,在您的let 语句中)确实复制对象。
  • @Bergi 为什么会这样?如何使用 let 语句复制对象?
  • @Bergi 你说得对,我注意到了!初始化时如何复制?

标签: javascript arrays typescript ionic-framework ecmascript-6


【解决方案1】:

我相信您不需要将函数的参数重新实例化为新的let 变量。照原样使用它们。

transformTable(table: Table, status: string): Table{
  table.checkins = table.checkins.map(checkin => {
      checkin.items = checkin.items.filter( item => item.statusOfItem == status )
      return checkin
   })
  return table
}

这也应该有效。无论如何,我一直都这样做,而且效果很好:)

【讨论】:

    【解决方案2】:

    对于任何感兴趣的人,感谢BergiJeremy 我最终得到了这个代码:

    private copyTableByStatus(table: Table, status: string): Table{
      // XXX: Weird, javascript can't deep copy. Object.assign() only creates
      // shallow copies. There should be something like Object.clone() ...
      let newTable: Table = JSON.parse(JSON.stringify(table));
      newTable.checkins = JSON.parse(JSON.stringify(table.checkins.map(
        checkin => {
          checkin.items = JSON.parse(JSON.stringify(checkin.items.filter(
            item => item.statusOItem == status
          )))
          return checkin;
        }
      )))
      return newTable;
    }
    

    谢谢你们俩。我不知道,javascript 不能复制对象! :( 太令人沮丧了...

    【讨论】:

    • 小记:使用扩展运算符来复制对象可能会更干净。 let newTable = { ...table };.
    • @Dieterg 据我所知,因为@Bergi 的评论...table 只会做一个浅拷贝。
    猜你喜欢
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 2018-03-26
    • 2016-03-27
    • 2022-01-14
    • 2022-07-06
    • 1970-01-01
    相关资源
    最近更新 更多