我有以下枚举
enum FunnelStage {
LOGIN
}
那么我有以下对象
const overall = {
[FunnelStage.LOGIN]: {count: 1}
}
overall[FunnelStage.Login].count = 2
稍后我想像这样迭代overall
对象
for (let funnelStage in overall) {
console.log(overall[funnelStage].count)
}
这会产生错误-Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record<FunnalStage, { count: number; }>'. No index signature with a parameter of type 'string' was found on type 'Record<FunnalStage, { count: number; }>'
如何实现循环?
我也试过这样做,但它给了我同样的错误
for (let funnelStageKey in Object.keys(overall) as Array<keyof typeof FunnalStage>) {
const count = overall[funnelStageKey].count;
console.log(count);
}
连接到Playground
1条答案
按热度按时间sczxawaw1#
你可以使用Object.entries方法来遍历整个对象的属性。然后你可以在for-of循环中解构键/值对,并使用键来访问相应的枚举值:
或者,您可以使用Object.keys方法取得索引键数组,然后使用map方法建立FunnelStage值的新数组:
然后,您可以逐一查看funnelStages数组,并使用值来存取整体对象中的Map属性: