Reputation: 323
I am trying to figure out a proper way to loop through an Object while using TypeScript. The following examples would be valid JavaScript but I do understand why it becomes a problem in TypeScript, however I am not finding the correct way to proceed with this task and I was wondering if I am thinking wrong about it.
My goal is to iterate through a two-level-deep Object and be able to access the item directly from the Object at the end, and not only its value.
Example:
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
}
}
// Trying with for-in
for (const cat in data) {
for (const item in cat) {
console.log(cat, item) // works just fine cause both are strings
console.log(data[cat][item]) // both cat and items are strings and not keys of Data.
}
}
// Trying with for-of
for (const cat of Object.keys(data)) {
for (const item of Object.keys(cat)) {
console.log(data[cat][item]) // Same, cat becomes just a string and not valid key of Data.
}
}
// Trying with forEach
Object.keys(data).forEach((cat) => {
Object.keys(cat).forEach(item => console.log(data[cat][item])) // same thing, cat is just a string and not exactly a key of Data
})
Thank you all :)
Upvotes: 0
Views: 95
Reputation: 395
See this:
for (let key of Object.keys(data.a)) {
console.log(data.a[key]);
This will log out all the keys of data.a
. You could do anything to each key by performing this loop through the keys and accessing those key values with data.a[key]
.
Upvotes: 0
Reputation: 156
I hate to use the "any" but in this code snippet i think its pretty safe to use duo to the if statments
Object.keys(data).forEach((key1 ) => {
if(key1 in data) {
Object.keys((data as any)[key1]).forEach((key2) => {
if(key2 in (data as any)[key1]) {
console.log((data as any)[key1][key2])
}
})
}
})
Upvotes: 1
Reputation: 7428
When you're iterating via Object.keys(someObject)
- you're retrieving keys, not objects.
for (let catKey of Object.keys(data)) {
for (let itemKey of Object.keys(data[catKey])) {
console.log(catKey, itemKey)
console.log(data[catKey][itemKey])
}
}
Upvotes: 2