TypeScript, Looping through a dictionary

后端 未结 8 829
慢半拍i
慢半拍i 2020-12-04 11:41

In my code, I have a couple of dictionaries (as suggested here) which is String indexed. Due to this being a bit of an improvised type, I was wondering if there any suggesti

相关标签:
8条回答
  • 2020-12-04 12:03

    Shortest way to get all dictionary/object values:

    Object.keys(dict).map(k => dict[k]);
    
    0 讨论(0)
  • 2020-12-04 12:03

    Ians Answer is good, but you should use const instead of let for the key because it never gets updated.

    for (const key in myDictionary) {
        let value = myDictionary[key];
        // Use `key` and `value`
    }
    
    0 讨论(0)
  • 2020-12-04 12:06

    To get the keys:

    function GetDictionaryKeysAsArray(dict: {[key: string]: string;}): string[] {
      let result: string[] = [];
      Object.keys(dict).map((key) =>
        result.push(key),
      );
      return result;
    }
    
    0 讨论(0)
  • 2020-12-04 12:10

    To loop over the key/values, use a for in loop:

    for (let key in myDictionary) {
        let value = myDictionary[key];
        // Use `key` and `value`
    }
    
    0 讨论(0)
  • 2020-12-04 12:13

    How about this?

    for (let [key, value] of Object.entries(obj)) {
        ...
    }
    
    0 讨论(0)
  • 2020-12-04 12:14

    If you just for in a object without if statement hasOwnProperty then you will get error from linter like:

    for (const key in myobj) {
       console.log(key);
    }
    
    WARNING in component.ts
    for (... in ...) statements must be filtered with an if statement
    

    So the solutions is use Object.keys and of instead.

    for (const key of Object.keys(myobj)) {
       console.log(key);
    }
    
    

    Hope this helper some one using a linter.

    0 讨论(0)
提交回复
热议问题