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

5 Answers

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

*/

 



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

*/


 



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

*/

 



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

*/

 



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

*/

 



answered Mar 23 by avibootz

Related questions

...