【问题标题】:is there a way to dynamically apply array mappers in TypeScript?有没有办法在 TypeScript 中动态应用数组映射器?
【发布时间】:2021-10-10 15:20:20
【问题描述】:

我需要帮助。我正在尝试从数组中获取数据,但每次我添加一个新的组过滤器(我正在使用自定义 Kendo 网格)时,我收到的是一个嵌套数组,如果我想获取这些数据,我需要添加一个新的“项目”数组上的映射方法。问题是我没有只有一个组过滤器,但我有太多了。我能做什么?

所以每次我都必须在 items 数组上添加另一个 map 方法,这不是很舒服。我的问题有解决方案吗?我可以很容易地得到组过滤器的编号。

【问题讨论】:

  • this.GridDataResult.data.forEach((x)=>{ this.selectedKeys += x.items.map((y)=> y.selectionKey) })
  • 您可以使用 flatMap 转换例如[ [1, 2], [3, 4] ] 到 [1, 2, 0, 3, 4, 0] 对于 arr.flatMap(v => [...v, 0])。在您的情况下,这应该具有相同的结果: const temp = this.GridDataResult.data .flatMap(x => x.items) .map(y => y.selectionKey)

标签: javascript arrays typescript dictionary


【解决方案1】:

您可以使用flatMap 转换,例如[ [1, 2], [3, 4] ][1, 2, 0, 3, 4, 0]arr.flatMap(v => [...v, 0])。在您的情况下,这应该具有相同的结果:

const temp = this.result.data
    .flatMap(x => x.array)
    .map(y => y.selections)

这使您的代码更具可读性,更易于维护和添加。

如果你真的想动态添加地图功能,你可以这样做:

const maps = [
    x => x.array,
    v => [v, v * 11],
    v => [v, -v],
    v => `num: ${v}`,
];

const data = [
    { array: [1, 2] },
    { array: [3] },
];

const temp = maps.reduce((data, map) => data.flat().map(map), data);
console.log(temp);

【讨论】:

    【解决方案2】:

    您可以通过这样替换第一个地图来删除 forEach:

    this.result.data.forEach((x)=>{
      this.selections += x.array.map((y)=> y.selections)
    })
    

    举个例子说明 this.result 和 this.selections 可能包含的内容会有所帮助

    【讨论】:

      猜你喜欢
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 2019-08-01
      • 2021-01-04
      • 1970-01-01
      • 2022-01-20
      相关资源
      最近更新 更多