Typescript枚举索引对象迭代对象

zrfyljdw  于 2022-12-05  发布在  TypeScript
关注(0)|答案(1)|浏览(178)

我有以下枚举

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

sczxawaw

sczxawaw1#

你可以使用Object.entries方法来遍历整个对象的属性。然后你可以在for-of循环中解构键/值对,并使用键来访问相应的枚举值:

for (const [key, value] of Object.entries(overall)) {
    console.log(FunnelStage[key], value.count);
}

或者,您可以使用Object.keys方法取得索引键数组,然后使用map方法建立FunnelStage值的新数组:

const keys = Object.keys(overall);
const funnelStages = keys.map(key => FunnelStage[key]);

然后,您可以逐一查看funnelStages数组,并使用值来存取整体对象中的Map属性:

for (const funnelStage of funnelStages) {
    console.log(funnelStage, overall[funnelStage].count);
}

相关问题