无法阅读财产标题'在访问嵌套对象时未定义

时间:2016-02-11 09:57:24

标签: javascript

我正在尝试在forEach循环中读取businessData[i].services[i].title中的值,但不断收到以下错误消息:TypeError: Cannot read property 'title' of undefined

如何正确读取services数组中的属性标题?

profileData和businessData对象

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函数

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

1 个答案:

答案 0 :(得分:1)

只需将服务[value.serviceId-1]和每一个密钥放在一起;因为Array从0索引开始。