【问题标题】:how to combine array of objects by value using reduce( ) in TypeScript如何在 TypeScript 中使用 reduce() 按值组合对象数组
【发布时间】:2022-11-24 00:42:08
【问题描述】:

我在 TypeScript 中使用 reduce() 时遇到问题。我想将具有相同键/值对的对象减少到一个数组中。

我正在尝试这样:

    const asdf = sections.reduce<{ [index: number]: any }>((res, section) => {
        return [
          ...res, //error here
          {
            [section.buildingId]: [
              ...(res[section.buildingId] || []),
              section,
            ],
          },
        ]
      },[]) //I think the problem lies here?!
    }

sections 是一个对象数组,所有对象都具有键 buildingId: number。 我怀疑 [] 的初始值是问题的根源,但我不太确定。

第三行给出了这个错误:

输入'{ [index: number]: any; }' 必须有一个返回 iterator.ts(2488) 的 'Symbol.iterator' 方法

这对我来说很奇怪,因为数字是可迭代的?!或不?

【问题讨论】:

  • 泛型类型错别字导致,应该是数组sections.reduce&lt;{ [index: number]: any }[]&gt;
  • 它将错误消息(与上面相同)移至此行 (res[section?.buildingId ? section.buildingId : 0] || []) 还有其他线索吗?我就是想不通..
  • 如果您将通用参数设置为 any[] (tsplay.dev/Wok6eW),您至少可以运行 javascript 代码 - 请验证它确实是您想要的(结果似乎有点难以置信) - 如果是,那么一个更具体的模板可以考虑论证。

标签: typescript


【解决方案1】:

将类型更改为数组:

const asdf = sections.reduce<Array<any>>((res, section) => {
    return [
      ...res,
      {
        [section.buildingId]: [
          ...(res[section.buildingId] || []),
          section,
        ],
      },
    ]
  },[])

【讨论】:

    猜你喜欢
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 2017-09-06
    • 1970-01-01
    相关资源
    最近更新 更多