在 TypeScript 中过滤对象数组

要在 TypeScript 中过滤对象数组:

  1. 在数组上调用 filter() 方法。
  2. 检查当前对象的属性是否满足条件。
  3. 返回的数组将只包含满足条件的对象。
const employees = [
  { name: 'Alice', department: 'accounting' },
  { name: 'Bob', department: 'human resources' },
  { name: 'Carl', department: 'accounting' },
];

const result = employees.filter((obj) => {
  return obj.department === 'accounting';
});

// ?️ [{name: 'Alice', department: 'accounting'},
//     {name: 'Carl', department: 'accounting'}]
console.log(result);

在 TypeScript 中过滤对象数组

我们传递给 Array.filter 方法的函数被数组中的每个元素(对象)调用。

在每次迭代中,我们检查对象上的部门属性是否等于会计并返回结果。

filter 方法返回一个仅包含元素的数组,回调函数为其返回一个真值。

如果条件从未满足,则 Array.filter 方法返回一个空数组。

请注意,我们不必键入对象数组,因为 TypeScript 能够在使用值声明数组时推断类型。

如果要声明一个空数组,请显式键入它。

const employees: { name: string; department: string }[] = [];

employees.push(
  { name: 'Alice', department: 'accounting' },
  { name: 'Bob', department: 'human resources' },
  { name: 'Carl', department: 'accounting' },
);

const result = employees.filter((obj) => {
  return obj.department === 'accounting';
});

// ?️ [{name: 'Alice', department: 'accounting'},
//     {name: 'Carl', department: 'accounting'}]
console.log(result);

我们初始化了一个空数组,所以我们必须显式地键入它。

如果我们初始化一个空数组并且没有显式键入它,TypeScript 会将其类型设置为 any[],这实际上会关闭所有类型检查。

如果我们只需要在数组中查找满足某个条件的单个对象,请使用 Array.find() 方法。

const employees = [
  { name: 'Alice', department: 'accounting' },
  { name: 'Bob', department: 'human resources' },
  { name: 'Carl', department: 'accounting' },
];

const result = employees.find((obj) => {
  return obj.name === 'Bob';
});

// ?️ {name: 'Bob', department: 'human resources'}
console.log(result);

console.log(result?.name); // ?️ "Bob"
console.log(result?.department); // ?️ "human resources"

在 TypeScript 中过滤对象数组

我们传递给 Array.find 方法的函数会为数组中的每个元素(对象)调用,直到它返回一个真值或遍历整个数组。

如果函数返回一个真值,则 find() 返回相应的数组元素并短路。

如果条件从未满足,则 find() 方法返回 undefined

请注意,我们在访问属性时使用了可选链。

这是必要的,因为我们无法确定条件是否满足。

我们可以使用类型保护来确定是否找到了匹配的对象。

const employees = [
  { name: 'Alice', department: 'accounting' },
  { name: 'Bob', department: 'human resources' },
  { name: 'Carl', department: 'accounting' },
];

const result = employees.find((obj) => {
  return obj.name === 'Bob';
});

if (result !== undefined) {
  // ✅ TypeScript knows that result is object

  // ?️ {name: 'Bob', department: 'human resources'}
  console.log(result);

  console.log(result?.name); // ?️ "Bob"
  console.log(result?.department); // ?️ "human resources"
}

如果 result 不等于 undefined,TypeScript 知道它是一个对象,所以它允许我们访问对象的属性。

Array.find() 方法返回满足条件的第一个数组元素。

即使有多个匹配元素,在回调函数返回一个真值后,该方法也会立即短路。