处理 Angular 2 App 中数组中某些对象缺少 属性

Handling Lack of Property in Some Objects in Array in Angular 2 App

我在我的 Angular 2 应用程序的一个组件中有一个包装在可观察对象中的方法,该方法旨在根据特定 属性 的布尔值过滤结果数组。我的方法如下所示:

    this.clientService.getAllClients()
        .subscribe(resRecordsData => {
            this.records = resRecordsData;
            this.inactiveRecords = this.records.filter(record => record.registration.active === false);
            this.records = this.inactiveRecords;
        },
        responseRecordsError => this.errorMsg = responseRecordsError);

当我 运行 这个时,我得到一个 "undefined" 错误:

EXCEPTION: Cannot read property 'active' of undefined

我假设这是因为并非集合中的所有条目都包含此 属性。所以我的问题是,我如何添加条件逻辑来处理我正在检查数组中的 属性 不存在的情况?

首先检查对象是否包含属性:

record => record.registration && record.registration.active === false;

var testItems = [{
  id: 1,
  detail: {
    name: 'test name1'
  }
},{
  id: 2,
  detail: {
    name: 'xxxx'
  }
}, {
  id: 3,
}];

console.log(testItems.filter(function(item) {
  return item.detail && item.detail.name.indexOf('test') > -1;
}))

您可以使用

检查对象上是否定义了属性
obj.hasOwnProperty('foo')

所以在你的情况下你可以做类似的事情

this.inactiveRecords = this.records.filter(

    record => {

        let registration = record.hasOwnProperty('registration') ? record.registration : false;

        if (registration && registration.hasOwnProperty('active')) {
            return registration.active === false;
        }

        return false; // Default return for when property is not defined.

    }

);

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty