Sebsemillia Sebsemillia - 1 month ago 7
Javascript Question

replace for in with regular for loop with objects

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++;
}
}

Answer

You're starting your loop from 0 while your first key in the whole object is 1.

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
  }
};

var keyLength = Object.keys(el).length;

// I've simplified the for loop
for (var i = 1; i <= keyLength; i++) {
  console.log(el[i].commonName);
}

Comments