Bobox
Bobox

Reputation: 21

Cannot read property '0' of undefined

getBrand: function(brandId) {
  for(var i=0; i<malls.length; i++) {
    for(var j=0;j<malls[i].brands.length; j++){
      //console.log(malls[i][brands[j]);
      //console.log(malls[i].brands[j].id);
      if(malls.brands[j].id==(brandId)){
        console.log(malls.brands[j].id);
        return malls.brands[j].id;
      }
    }
  }
}

I need help please, and in my console i get this message:TypeError: Cannot read property '0' of undefined

Upvotes: 0

Views: 1663

Answers (3)

Edwin Reynoso
Edwin Reynoso

Reputation: 1541

You should be able to do this and avoid the fuss.

for(var mall of malls) {
    for(var brand of mall) {
        if(brand.id == brandId) return brand.id;
    }
}

Upvotes: 0

Ram
Ram

Reputation: 144739

It seems you have an array of objects and each object has a brands property that contains an array of objects. Your second for loop assumes the malls array itself has brands property which is not true. As the malls.brands is undefined you get that error.

Change:

if (malls.brands[j].id==(brandId)) {

to:

if (malls[i].brands[j].id==(brandId)) {

Upvotes: 1

Santiago Hern&#225;ndez
Santiago Hern&#225;ndez

Reputation: 5646

as @Vohuman pointed, i think you should write malls[i].brands[j] in order to access the array brands inside your object malls[i], otherwise you're accessing to the whole malls objects array which doesn't have a brands array property

getBrand: function(brandId) {
  for(var i=0; i<malls.length; i++) {
    for(var j=0;j<malls[i].brands.length; j++){
      if(malls[i].brands[j].id==(brandId)){
        console.log(malls[i].brands[j].id);
        return malls[i].brands[j].id;
      }
    }
  }
}

Upvotes: 0

Related Questions