Explain Codes LogoExplain Codes Logo

How to iterate over a JavaScript object?

javascript
iteration
object-entries
map
Anton ShumikhinbyAnton ShumikhinΒ·Sep 22, 2024
⚑TLDR

Iterate through a JavaScript object with for...in or pair Object.keys() with .forEach(). The for...in loop traverses enumerable properties while Object.keys() furnishes an array of keys for iteration.

for...in example:

const obj = {a: 1, b: 2}; for (const key in obj) { // Time to unlock the treasure chest πŸ” console.log(key, obj[key]); }

Object.keys() example:

const obj = {a: 1, b: 2}; Object.keys(obj).forEach(key => { // Keys are the pathway to the secret knowledge πŸ—οΈ console.log(key, obj[key]); });

Iteration techniques to save the day

Paring keys and values with Object.entries()

Object.entries() pairs keys and values, a best friend to for...of or forEach():

const obj = {a: 1, b: 2}; // What can be better than keys? Keys with values! πŸ—οΈ+πŸ’Ό Object.entries(obj).forEach(([key, value]) => console.log(key, value));

Discovering maps: Not just for pirates

Forget objects, switch to Map for predictable key ordering. Who said only pirates love good maps?

let myMap = new Map(Object.entries({a: 1, b: 2})); // No treasure maps here, just keys and values πŸ΄β€β˜ οΈ for (let [key, value] of myMap) { console.log(key, value); }

Filtering like a coffee master

Brew your code like coffee with filter and Object.keys for conditional property iteration:

const obj = {a: 1, b: 2, c: 3}; // Let's filter out the bitterness (key 'b') β˜• const filteredKeys = Object.keys(obj).filter(key => key !== 'b'); filteredKeys.forEach(key => console.log(key, obj[key]));

From noob to pro: Iteration tips

Order is a luxury

Objects are anarchic, the property order is not guaranteed in JavaScript. Maps bring order to the chaos.

Prototype pitfalls

for...in brings its baggage from its prototype chain. Remember to use obj.hasOwnProperty(key) to only get what's yours.

The invisibility cloak

Object.entries() and Object.keys() only deal with visible properties. For secrets, you must summon Object.getOwnPropertyNames().

Turbo mode

For large objects, speed matters! Remember to benchmark your iteration methods.

Advanced Iterations: Going deeper

Dealing with JSON data

When working with JSON objects, transform them into Maps for efficient CRUD operations. Because, who doesn't like efficiency?

let jsonData = '{"name": "John", "age": 30}'; let userMap = new Map(Object.entries(JSON.parse(jsonData)));

Merging with frameworks

Frameworks like React and Angular offer their own iteration helpers. They say: "When in Rome, do as the Romans do."

Proxies for dynamic properties

For the thrill-seekers who play with dynamic or computed properties, use Proxy objects. You'll love the adrenaline rush!