Use let k: keyof T and a for-in loop to iterate objects when you know exactly what the keys will be. Be aware that any objects your function receives as parameters might have additional keys. Use Object. entries to iterate over the keys and values of any object.
Object. key(). It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.
To loop over the key/values, use a for in
loop:
for (let key in myDictionary) {
let value = myDictionary[key];
// Use `key` and `value`
}
< ES 2017:
Object.keys(obj).forEach(key => {
let value = obj[key];
});
>= ES 2017:
Object.entries(obj).forEach(
([key, value]) => console.log(key, value)
);
How about this?
for (let [key, value] of Object.entries(obj)) {
...
}
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];
}
}
Shortest way to get all dictionary/object values:
Object.keys(dict).map(k => dict[k]);
Or this ways:
Object.entries(dict).map([k,v] => /* ... */);
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`
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With