How to iterate over a collection of key-value pairs (associative array) in JavaScript

5 Answers

0 votes
// 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

*/

 



answered Mar 23 by avibootz
0 votes
// 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

*/

 



answered Mar 23 by avibootz
0 votes
// 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

*/

 



answered Mar 23 by avibootz
0 votes
// 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

*/

 



answered Mar 23 by avibootz
0 votes
// 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

*/

 



answered Mar 23 by avibootz

Related questions

...