TypeScript, Looping through a dictionary

后端 未结 8 830
慢半拍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:17

    < ES 2017:

    Object.keys(obj).forEach(key => {
      let value = obj[key];
    });
    

    >= ES 2017:

    Object.entries(obj).forEach(
      ([key, value]) => console.log(key, value)
    );
    
    0 讨论(0)
  • 2020-12-04 12:18

    There is one caveat to the key/value loop that Ian mentioned. If it is possible that the Objects may have attributes attached to their Prototype, and when you use the in operator, these attributes will be included. So you will want to make sure that the key is an attribute of your instance, and not of the prototype. Older IEs are known for having indexof(v) show up as a key.

    for (const key in myDictionary) {
        if (myDictionary.hasOwnProperty(key)) {
            let value = myDictionary[key];
        }
    }
    
    0 讨论(0)
提交回复
热议问题