For some reason it's returning both the key and value an excessive number of times. What am I doing wrong?
function loopAnArrayOfObjects(arrayOfObjects) {
for (var i = 0; i < arrayOfObjects.length; i++) {
for (var key in arrayOfObjects) {
console.log(arrayOfObjects[key]);
}
}
}
loopAnArrayOfObjects([{a: 1, b: 2}, {z: 5, y: 6}, {q: 14} ]);
// expected console output:
// 1
// 2
// 5
// 6
// 14
loopAnArrayOfObjects([{queue: false, stack: true}, {fish: 'swims'}, {shirt: 's', pop: 'p', eye: 'e'} ]);
// expected console output:
// false
// true
// swims
// s
// p
// e
2 Answers 2
In each iteration, the current element/object is arrayOfObjects[i], which is what you should be using.
function loopAnArrayOfObjects(arrayOfObjects) {
for (var i = 0; i < arrayOfObjects.length; i++) {
for (var key in arrayOfObjects[i]) {
console.log(arrayOfObjects[i][key]);
}
}
}
loopAnArrayOfObjects([{queue: false, stack: true}, {fish: 'swims'}, {shirt: 's', pop: 'p', eye: 'e'} ]);
Alternatively, you can use for ... of to loop over just the elements without the index.
function loopAnArrayOfObjects(arrayOfObjects) {
for(const obj of arrayOfObjects){
for (const key in obj) {
console.log(obj[key]);
}
}
}
loopAnArrayOfObjects([{queue: false, stack: true}, {fish: 'swims'}, {shirt: 's', pop: 'p', eye: 'e'} ]);
1 Comment
Since you are looping over arrays, it's best these days to do it with one of the Array.prototype methods. .forEach() is a great replacement for traditional counting loops because it does away with the need to set up and manage a counter and instead gives you direct access to the elements within the array. This simplification can often remove closures that will often cause problems or just make it easier to understand what you are working with. Then, when needing to loop over the object keys, you can use a for/in loop to also make it much simpler.
loopAnArrayOfObjects([{a: 1, b: 2}, {z: 5, y: 6}, {q: 14} ]);
// console output:
// 1
// 2
// 5
// 6
// 14
loopAnArrayOfObjects([{queue: false, stack: true}, {fish: 'swims'}, {shirt: 's', pop: 'p', eye: 'e'} ]);
// console output:
// false
// true
// swims
// s
// p
// e
function loopAnArrayOfObjects(ary){
ary.forEach(function(arrayItem){
// This will be the objects in the array
// Now, set up a secondary loop to go over the keys in the object
for(key in arrayItem){
console.log(arrayItem[key]);
}
});
}
for (var key in arrayOfObjects[i]) { console.log(arrayOfObjects[i][key]);?.reduce()to remove the counters too:[{a: 1, b: 2}, {z: 5, y: 6}, {q: 14} ].reduce((acc,next)=>{for(key in next) acc.push(next[key]); return acc;},[])