Contact: aviboots(AT)netvision.net.il
40,764 questions
53,140 answers
573 users
// Object.entries() + for...of (Modern and clean) const obj: Record<string, number> = { d: 4, a: 1, c: 3, b: 2 }; for (const [key, value] of Object.entries(obj)) { console.log(key, value); } /* run: d 4 a 1 c 3 b 2 */
// for...in loop (Classic) // Iterates over all enumerable properties, // including those on the prototype chain. const obj2: Record<string, number> = { d: 4, a: 1, c: 3, b: 2 }; for (const key in obj2) { const value = obj2[key]; // value is number console.log(key, value); } /* run: d 4 a 1 c 3 b 2 */
// Object.keys() + forEach() // Gets an array of keys, then you manually access values. const obj3: Record<string, number> = { d: 4, a: 1, c: 3, b: 2 }; Object.keys(obj3).forEach((key: string) => { console.log(key, obj3[key]); }); /* run: d 4 a 1 c 3 b 2 */
// Object.values() (Values only) const obj4: Record<string, number> = { d: 4, a: 1, c: 3, b: 2 }; for (const value of Object.values(obj4)) { console.log(value); } /* run: 4 1 3 2 */
// Iterating over a Map const map: Map<string, number> = new Map([ ["a", 1], ["b", 2], ["c", 3], ["d", 4] ]); for (const [key, value] of map) { console.log(key, value); } /* run: a 1 b 2 c 3 d 4 */