添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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 suggestions on how I would be able to loop through each key (or value, all I need the keys for anyway). Any help appreciated!

myDictionary: { [index: string]: any; } = {};
                Did you try: for (var key in myDictionary) { }? Inside the loop, you'd use key to get the key, and myDictionary[key] to get the value
– Ian
                Apr 23, 2013 at 16:15
                @Ian Just tried that, doesn't seem to be working. No errors, but nothing runs within the statement
– ben657
                Apr 23, 2013 at 16:21
                @Ian Ah sorry, some code elsewhere was messing with it. That works perfectly! Care to make it an answer so I can choose it?
– ben657
                Apr 23, 2013 at 16:38
                This isn't safe in general; it needs the hasOwnProperty test (as in Jamie Stark's answer) or something else.
– Don Hatch
                Feb 3, 2016 at 19:30
                @DonHatch It's actually very safe in general. It's not safe in very specific cases (like when you include libraries which modify prototypes incorrectly, or purposely modify prototypes incorrectly). It's up to the developer whether to bloat their code with most-likely-unnecessary checks
– Ian
                Feb 3, 2016 at 19:38
                @Ian The problem is that there are too many libraries which do modify object prototypes. It seems a bad idea to advocate this type of pattern when much better simple alternatives exist, such as Object.keys(target).forEach(key => { let value = target(key); /* Use key, value here */ });. If you must show this method, at least mention the risks and better alternatives for those who don't yet know better.
– Yona Appletree
                Apr 13, 2016 at 0:08
                We already have es6 and TypeScript. Why does the problem of writing hasOwnProperty all the time remain unresolved? Even in 2017 and with all attention to JS. I am so disappointed.
– Gherman
                Sep 25, 2017 at 13:10
                This is the solution I was looking for as it will allow me to sort the keys before iteration
– Andrew
                Oct 18, 2016 at 15:57
                This is what I needed to get past the Typescript error on obj[key] "No index signature..." because I explicitly set my obj type as { [key: string]: string } and not wanted to use { [key: string]: any }.  With this I can just access 'value'.  Thanks
– ggedde
                Nov 6, 2019 at 10:31
                this is the only valid way I've found so far to iterate through non string key index types
– nemo
                Oct 11, 2020 at 11:30
                This should be at the top. It's clean, it looks like a loop should look and it does not iterate over the prototype chain.
– Ruslan Plastun
                Aug 20, 2021 at 10:49
                @RadonRosborough It seems that oftentimes, even if defining the object, when looping through the object with this pattern, it loses the type safety for key and value. Or at least the interconnectedness of key and value type safety. Just curious what the pattern is to define the types for key and value if we want to be more explicit. Or is that not an option because as you said... it is self defining
– wongz
                Dec 15, 2021 at 4:24

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];
                Not trying to split hairs, but since we're talking type script, shouldn't you use let key instead of var key?  Nice answer thank you.
– Luke Dupin
                Mar 11, 2016 at 1:03
                It's better to not call the hasOwnProperty check from the target object, instead do this: ...if (Object.prototype.hasOwnProperty.call(myDictionary, key))... Else, if you are using eslint with no-prototype-builtins rule, it will emit an error.
– sceee
                Apr 30, 2020 at 6:38

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.

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`

To get the keys:

function GetDictionaryKeysAsArray(dict: {[key: string]: string;}): string[] {
  let result: string[] = [];
  Object.keys(dict).map((key) =>
    result.push(key),
  return result;

this is my function, i hope this help

function recordToArray<TypeOfSchema>(
  data: Record<string, TypeOfSchema>
): Array<TypeOfSchema> {
  return Object.keys(data).map((key: string) => ({ id: key, ...data[key] }));
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.