Contact: aviboots(AT)netvision.net.il
40,756 questions
53,124 answers
573 users
// Object.entries() + for...of (Modern and clean) const obj = { 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 obj = { d: 4, a: 1, c: 3, b: 2 }; for (const key in obj) { const value = obj[key]; 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 obj = { d: 4, a: 1, c: 3, b: 2 }; Object.keys(obj).forEach(key => { console.log(key, obj[key]); }); /* run: d 4 a 1 c 3 b 2 */
// Object.values() (Values only) const obj = { d: 4, a: 1, c: 3, b: 2 }; for (const value of Object.values(obj)) { console.log(value); } /* run: 4 1 3 2 */
// Iterating over a Map const map = 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 */