Iterating

How to iterate most common data structures in JavaScript.

The for-in loop

This loop has been created to iterate over object properties. It’s easy to use, and you have the key on each iteration.

1
2
3
4
5
6
7
8
9
const object = {
prop1: 'bar',
prop2: 'foo'
}
for(const k in object){
console.log(k, object[k]);
}
// prop1 bar
// prop2 foo

Now suppose the next object:

1
2
3
4
5
6
7
8
const objeto = {
prop1: {
prop1: 'foo',
prop2: [1,2,'bar']
},
prop2: 123,
prop3: ['abc','def',{ prop1: 'foo', prop2: 'bar'}]
}

You could use for-in as well, but in the proper way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const iterateRecursive = o => {
if(typeof o !== 'object'){
console.error('Use an object!');
} else {
for (const k in o){
if (typeof o[k] === 'object' && o[k] !== null){
iterateRecursive(o[k]);
} else {
console.log(k,o[k]);
}
}
}
}

iterateRecursive(objeto);

References