Looping through objects
Manchmal möchte man durch Objekte loopen, was eigentlich gar nicht wirklich geht. Daher wandelt man Objekte zuerst in Arrays um und verwendet dann eine Schleife.
Ein Objekt kann mit drei Methoden in einen Array umgewandelt werden:
Object.keys()Object.values()Object.entries()
Object.keys
Section titled “Object.keys”Object.keys() erstellt einen Array, der die Eigenschaften eines Objekts enthält.
const fruits = { apple: 28, orange: 17, pear: 54,};
const keys = Object.keys(fruits);console.log(keys); // ["apple", "orange", "pear"]Object.values
Section titled “Object.values”Object.values erstellt einen Array, der die Werte jeder Eigenschaft eines Objekts enthält.
const fruits = { apple: 28, orange: 17, pear: 54,}
const values = Object.values(fruits);console.log(values); // [28, 17, 54]Object.entries
Section titled “Object.entries”Object.entries() erstellt einen Array aus Arrays. Jeder innere Array hat zwei Elemente, der erste ist die Eigenschaft, der zweite der Wert.
const fruits = { apple: 28, orange: 17, pear: 54,}
const entries = Object.entries(fruits);console.log(entries);// [ ["apple", 28], ["orange", 17], ["pear", 54] ]Looping through the converted array
Section titled “Looping through the converted array”Nach dem Umwandeln kann man wie durch einen normalen Array loopen.
keys
const keys = Object.keys(fruits);for (const key of keys) { console.log(key);}// apple// orange// pearvalues
const values = Object.values(fruits);for (const value of values) { console.log(value);}// 28// 17// 54entries
Wenn man Object.entries() benutzt, ist es praktisch, die Arrays in Eigenschaft und Wert zu trennen (destructuring).
const entries = Object.entries(fruits);// ergibt [ ["apple", 28], ["orange", 17], ["pear", 54] ]for (const [fruit, count] of entries) { console.log(`There are ${count} ${fruit}s in the basket.`);};// There are 28 apples in the basket.// There are 17 oranges in the basket.// There are 54 pears in the basket.