0

I have a service which populates my associative array in typescript,

fun populateData(){
let tempArr;
tempArr = [];
this.service.get('Post', 1, 'true').subscribe(
        (response) => {
          this.loadingIcon = false;

          for (let i = 0; i < response.results.length; i++) {
             tempList = response.results[i]['tags'];
             for ( let iter of tempList){
               if ( iter in tempArr) {
                 tempArr[iter] = tempArr[iter] + 1;
               }else {
                 tempArr[iter] = 1;
               }
             }
          }
        },
        (error) => {
          if (error['status'] === 401) {
            localStorage.clear();
            this.router.navigateByUrl('/login');
          } else {
            this.router.navigateByUrl('/error');
          }
        }
      );
      console.log(tempArr);
        /*
          This function is inside a class, once I iterate get access to tempArr I will be assigning the tempArr data to a class variable like

       for (items in tempArr){
            this.data.push(items, tempArr[items]);
       }
        */
}

I'm able to populate my associative array with the service above which gives the following output in console,

tempArr in the console log output

I'm not able to iterate through this array, I tried a couple of methods like the following,

for ( const key in tempArr) {
      console.log(key + ':' + tempArr[key]);
    }

I want both they key and values from the array.

5
  • 1
    Is there a reason you're not using an object? They're made for this exact purpose. Commented Mar 19, 2018 at 18:33
  • @Gustorn I'm not sure of how to use object for this, any pointers will be of great help. Commented Mar 19, 2018 at 18:36
  • I'd have to see how tempArr is constructed Commented Mar 19, 2018 at 18:38
  • @Gustorn I've updated the question, with the tempArr declarations Commented Mar 19, 2018 at 18:46
  • you are not using array but rather plain object, and to iterate through all pairs of (key, value) you can use ES7 Object.entries method. Commented Mar 20, 2018 at 3:31

1 Answer 1

3

TypeScript generally assumes that the keys to arrays are numbers. What you were doing might work but it's not very idiomatic. I'm not going to rewrite your whole function but here are a few pointers:

When constructing your associative array (map for short from now on) you should try using an object instead of an array:

const tagCounts: { [key: string]: number } = {};
for (const result of response.results) {
    for (const tag of result.tags) {
        tagCounts[tag] = (tagCounts[tag] || 0) + 1;
    }
}

Then you can iterate the result with:

for (const tag of Object.keys(tagCounts)) {
    const count = tagCounts[tag];
    // Other stuff here
}

Or if you have polyfills for Object.entries then with:

for (const [tag, count] of Object.entries(tagCounts)) {
    // Other stuff here
}

Looking at your code, this.data.push also seems wrong: it will add a string and a number to your data array which is almost certainly not what you want. You might want to consider converting data to an object as well if you want to store key-value pairs.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried this one, however while trying to iterate using Object.keys(tagCounts) it is not entering the for loop. I can see the data in the tagCounts object in console log, i tired printing Object.keys(tagCounts) which is printing an empty array of size zero.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.