I need help with looping through an Object in TypeScript. While the following examples work in JavaScript, I understand why they pose a problem in TypeScript. Unfortunately, I am struggling to find the correct approach to solve this issue. Am I approaching this problem incorrectly?
My objective is to iterate through a two-level-deep Object and be able to directly access the item from the Object at the end, rather than just its value.
For instance:
interface A {
abc: number
acd: number
}
interface B {
bcd: number
bde: number
}
interface C {
cde: number
cef: number
}
interface Data {
a: A
b: B
c: C
}
const data: Data = {
a: {
abc: 1,
acd: 2
},
b: {
bcd: 3,
bde: 4
},
c: {
cde: 5,
cef: 6
}
}
// Attempting with for-in loop
for (const cat in data) {
for (const item in cat) {
console.log(cat, item) // This works fine because both are strings
console.log(data[cat][item]) // However, 'cat' and 'item' are treated as strings, not keys of Data.
}
}
// Trying with for-of loop
for (const cat of Object.keys(data)) {
for (const item of Object.keys(cat)) {
console.log(data[cat][item]) // Similarly, 'cat' becomes just a string and not a valid key of Data.
}
}
// Experimenting with forEach method
Object.keys(data).forEach((cat) => {
Object.keys(cat).forEach(item => console.log(data[cat][item])) // In this case too, 'cat' is considered only a string and not a key of Data
})
Thank you for your assistance :)