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