Html TypeScript,遍历字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16174182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:47:57  来源:igfitidea点击:

TypeScript, Looping through a dictionary

javascripthtmltypescript

提问by ben657

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; } = {};

回答by Ian

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

要遍历键/值,请使用for in循环:

for (let key in myDictionary) {
    let value = myDictionary[key];
    // Use `key` and `value`
}

回答by Stephen Paul

< ES 2017:

< ES 2017

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

>= ES 2017:

>= ES 2017

Object.entries(obj).forEach(
  ([key, value]) => console.log(key, value);
);

回答by Radon Rosborough

How about this?

这个怎么样?

for (let [key, value] of Object.entries(obj)) {
    ...
}

回答by Jamie Starke

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 inoperator, 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.

Ian 提到的键/值循环有一个警告。如果对象可能具有附加到其原型的属性,并且当您使用in运算符时,这些属性将被包括在内。因此,您需要确保键是实例的属性,而不是原型的属性。较旧的 IE 以indexof(v)显示为键而闻名。

for (const key in myDictionary) {
    if (myDictionary.hasOwnProperty(key)) {
        let value = myDictionary[key];
    }
}

回答by k06a

Shortest way to get all dictionary/object values:

获取所有字典/对象值的最短方法:

Object.keys(dict).map(k => dict[k]);

回答by Ribeiro

To get the keys:

获取密钥:

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