J
J
Jirafek2021-12-15 19:51:53
JavaScript
Jirafek, 2021-12-15 19:51:53

How to iterate through nested objects?

I am using typescript. I have an object with sub objects, and I don't know how to iterate over the values ​​of sub objects.
This is how I was able to get to the keys under the object:

let key: keyof IFilter;
for(key in filterObject) {
                    Object.keys(filterObject[key]).forEach(filt => {
                        console.log(filt) // тут выводит ключ под объекта
                        console.log(filterObject[key][filt]) // даёт ошибку, оставил чуть ниже
                    })
            }


Error :
Элемент неявно имеет тип "any", так как выражение типа "string" не может использоваться для индексации типа "string | boolean |

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-12-15
@bingo347

First, Object.keys() returns a string[] type regardless of the object type.
You can use the wrapper from my lib, which has the correct types:
https://www.npmjs.com/package/@lambda-fn/basis
https: //github.com/bingo347/lambda-fn/blob/main/do...
Secondly, judging by the error, you have not only subobjects in your object, but also strings and boolean fields.
It is necessary to check that there is an object in a particular field, and in order for TS to understand such a check, it is better to do it through type guard
. Again, you can take it from me:
https://www.npmjs.com/package/@lambda-fn/type-guards
https://github.com/bingo347/lambda-fn/blob/main/do...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question