How can I peform this filter but only check each condition if the value is not undefined?
For example, if taxId is undefined I want to ignore it instead of filtering by it.

this.subAgencies = demoSubAgencies.filter(function(subAgency) {
  return subAgency.subAgencyName == agencyName
    && subAgency.taxId == taxId
    && subAgency.accountNumber == accountNumber;
});

推荐答案

您可以try 基于值的存在动态构建筛选条件.您可以使用&&运算符链接到条件,但只有在相应的值不是undefined时才包括条件.

下面是一个如何做到这一点的例子:

this.subAgencies = demoSubAgencies.filter(function(subAgency) {
  let condition = true; // Start with a true condition

  // Check if agencyName is defined, and if so, include it in the condition
  if (agencyName !== undefined) {
    condition = condition && subAgency.subAgencyName == agencyName;
  }

  // Check if taxId is defined, and if so, include it in the condition
  if (taxId !== undefined) {
    condition = condition && subAgency.taxId == taxId;
  }

  // Check if accountNumber is defined, and if so, include it in the condition
  if (accountNumber !== undefined) {
    condition = condition && subAgency.accountNumber == accountNumber;
  }

  return condition;
});

Typescript相关问答推荐

具有条件通用props 的react 类型脚本组件错误地推断类型

TypScript ' NoInfer '类型未按预期工作

rxjs forkJoin在错误后不会停止后续请求

在嵌套属性中使用Required

具有泛型类型和缺省值的键

是否使用非显式名称隔离在对象属性上声明的接口的内部类型?

Material UI / MUI系统:我如何告诉TypeScript主题是由提供程序传递的?

在对象中将缺省值设置为空值

从泛型类型引用推断的文本类型

以Angular 执行其他组件的函数

下载量怎么会超过下载量?

如何从MAT-FORM-FIELD-MAT-SELECT中移除焦点?

NPM使用Vite Reaction应用程序运行预览有效,但我无法将其部署到Netlify

使用ngfor循环时,数据未绑定到表

打字脚本错误:`不扩展[Type]`,而不是直接使用`[Type]`

使用强制转换编写打字函数的惯用方法

在类型{}上找不到带有string类型参数的索引签名 - TypeScript

如何按成员资格排除或 Select 元组?

如何在 TypeScript 类型定义中简化定义长联合类型

使用嵌套属性和动态执行时,Typescript 给出交集而不是并集