Skip to content
Advertisement

Access values from keys in typescript

In my typescript application, I have the config.json in the following format:

JavaScript

Now, in my .ts file, I want to read these key value pairs, and I am using the following code:

JavaScript

Screenshot from console of eventfilters

I am trying to compare the values in ‘if’ statement, using the following ‘eventfilters[i][keys[j]]’. However, its throwing the following error ‘Type ‘Object’ cannot be used as an index type.’.

However, when I use the following statement in the browser console, it returns me the value of the key, ‘eventfilters[0][0]’

And due to the version of the typescript and ecmascript, I cannot use the following:

Object.values(eventfilters[i]); OR Object.entries(eventfilters[i]);

Apologies for the long question and thanks in advance.

Advertisement

Answer

Your “keys” variable it is declared as an Object[], and it cannot be used as an index in an array.

You should use a string array in that case:

JavaScript

But, as you don’t have a class to store the objects, it’s wont work either. The angular can’t trust that all the index from the objects it will be always a string.

So, in this case, you can abandon the index approach and use something like:

JavaScript

Approach not using Object.entries

You can also force a type to the records on the EventFilters array.

JavaScript
Advertisement