Skip to content

Access values from keys in typescript

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

EventFilters": [
      {
        "Name": "AppLaunch",
        "Version": "2"
      },
      {
        "Name": "messageDisplayed",
        "Version": "2"
      },
      {
        "ID": "40021",
        "Version": "2"
      }
    ]

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

[![let eventfilters: Object[] = this.getEventFilters();           // this method reads the event filters from the config, as shown in the image

let keys: Object[];
for (let i: number = 0; i < eventfilters.length; i++) {
    keys = Object.keys(eventfilters[i]);
    for (let j: number = 0; j < keys.length; j++) {
        if(eventfilters[i][keys[j]] === [/*Parameter 2 to compare*/]){
            //do something
        }
    }
}]

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.

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:

let keys: string[];

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:

EventFilters.forEach(obj => {
    Object.entries(obj).forEach(([key, value]) => {
        console.log('${key} ${value}');
    });
});

Approach not using Object.entries

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

const EventFilters: Record<string, any> = [
    {
        "Name": "AppLaunch",
        "Version": "2"
    },
    {
        "Name": "messageDisplayed",
        "Version": "2"
    },
    {
        "ID": "40021",
        "Version": "2"
    }
];


let keys: any[];
for (let i: number = 0; i < EventFilters.length; i++) {
    for (const key in EventFilters[i]) {
        console.log(key);
        console.log(EventFilters[i][key]);
    };
}