I'm currently trying to replace a for in loop that I have with a regular for loop out of curiosity, but with no success. I always get undefined. Is this even possible with javascript objects?
example object I loop over:
var el = {
1: {type: "fish", commonName: "clownfish", scientificName: "sdasd", gender: "m", price: 1.99},
2: {type: "fish", commonName: "dragonfish", scientificName: "dada", gender: "f", price: 2.99}
};
My working for in approach:
for (var element in el) {
if (el[element].type === type && el.hasOwnProperty(element)) {
elementNum++;
}
}
The simple for loop approach that always gets me Cannot read property 'type' of undefined:
for(var i = 0, x = Object.keys(el).length; i < x; i++) {
if (el[i].type === type && el.hasOwnProperty(i)) {
elementNum++;
}
}
(el[i].type === type && el.hasOwnProperty(i))so that it doesn't check for.typeifel[i]doesn't exist (because javascript stops looking through theif ANDstatement if it finds one that is false.