methuselah
methuselah

Reputation: 13206

Cannot read property 'title' of undefined when accessing nested object

I am trying to read the value in businessData[i].services[i].title in my forEach loop but keep getting the following error message: TypeError: Cannot read property 'title' of undefined.

How do I correctly read the property title in the services array?

profileData and businessData object

var profileData = [{
  id: 1,
  notifications: [{
    type: 'payment-received',
    businessId: 1,
    serviceId: 2,
    timestamp: 1455177629000,
    text: ''
  }, {
    type: 'accepted-booking',
    businessId: 1,
    serviceId: 2,
    timestamp: 1454661898000,
    text: ''
  }, {
    type: 'received-booking',
    businessId: 1,
    serviceId: 1,
    timestamp: 1454661897000,
    text: ''
  }]
}];

var businessData = [{
  id: 1,
  categoryId: 1,
  name: 'Japan Center Garage',
  services: [{
    id: 1,
    businessId: 1,
    title: 'Brake Fluid Refresh'
  }, {
    id: 2,
    businessId: 1,
    title: 'Diagnostics'
  }]
}, {
  id: 2,
  categoryId: 1,
  name: 'Rex Garage',
  services: [{
    id: 3,
    businessId: 1,
    title: 'Coolant Refresh'
  }, {
    id: 4,
    businessId: 1
    title: 'Oil Change'
  }]
}, {
  id: 3,
  categoryId: 1,
  name: 'Mission & Bartlett Garage',
  services: [{
    id: 5,
    businessId: 1,
    title: 'MOT'
  }, {
    id: 6,
    businessId: 1,
    title: 'Summer Check'
  }, {
    id: 7,
    businessId: 1,
    title: 'Winter Check'
  }]
}]

getSelectedProfile function

getSelectedProfile: function(profileId) {
  var profileId = parseInt(profileId);
  for (var i = 0; i < profileData.length; i++) {
    var profile = profileData[i];
    if (profile.id === profileId) {
      profile.notifications.forEach(function(value) {
        console.log(businessData[1].services)
        if (value.type === "payment-received") {
          value.text = businessData[value.businessId].name + " has received payment for the " + businessData[value.businessId].services[value.serviceId].title + " service.";
        }
        else
        if (value.type === "accepted-booking") {
          value.text = businessData[value.businessId].name + " has accepted your booking for the " + businessData[value.businessId].services[value.serviceId].title + " service.";
        }
        else
        if (value.type === "received-booking") {
          value.text = businessData[value.businessId].name + " has received your booking for the " + businessData[value.businessId].services[value.serviceId].title + " service.";
        }
      });
      return profile;
    }
  }
}

Upvotes: 0

Views: 1288

Answers (1)

Abhishek
Abhishek

Reputation: 36

Just put services[value.serviceId-1] and for every single key as well; because Array starts from 0 index.

Upvotes: 2

Related Questions