I need to iterate over a large object which is just typed as "object". It contains an unknown number of objects of the same type.
In older posts I had found solutions using a generator within a custom Symbol.iterator function to make the large object iterable with a for..of loop.
But it seems to me, now in 2017, just using Object.keys is actually easier:
Object.keys(bigObject).forEach((key:string)=>{ console.log(bigObject[key]); });
This actually runs just fine! But the TypeScript compiler keeps giving me the error "error TS7017: Element implicitly h as an 'any' type because type '{}' has no index signature"
Does anybody have an idea what I am missing here? Or what is the current best practice to do such an iteration with ES2015 and TypeScript (2.2.2)?
You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.
To iterate over array of objects in TypeScript, we can use the for-of loop. to loop through the products array. product is the object being iterated through, so we can get the productDesc property from the object.
It's explained in detail here: " IterableIterator is an interface defined by TypeScript that combines the contracts of Iterables and Iterator into one. This is because, in some cases, it makes sense to have the Iterable as an Iterator itself, removing the need to have an external class that serves as the iterator."
When looking at the Typescript documentation (Typescript: Iterators and Generators), we see that the for..in syntax will iterate over the keys of the object.
for..in returns a list of keys on the object being iterated, whereas for..of returns a list of values of the numeric properties of the object being iterated.
We can use that to our advantage to index into our object and get the strongly typed value:
// Go through each key of the indexed object: for (const key in indexedObject) { // Get the indexed item by the key: const indexedItem = indexedObject[key]; // Now we have the item. // Use it... }
We can use that to get an elegant solution to the question:
// Go through each key in the bigObject: for (const key in bigObject) { // Get the strongly typed value with this name: const value = bigObject[key]; // Now we have the the strongly typed value for this key (depending on how bigObject was typed in the first place). // Do something interesting with the property of bigObject... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With