如何在 TypeScript 中查找数组中的对象

在 TypeScript 中查找数组中的对象

How to find an Object in an Array in TypeScript

要在数组中查找对象:

  1. 调用find()数组上的方法,向其传递一个函数。
  2. 该函数应返回对相关属性的相等性检查。
  3. find()方法返回数组中满足条件的第一个值。
索引.ts
const arr = [ { id: 1, country: 'Mexico' }, { id: 2, country: 'Germany' }, { id: 3, country: 'Mexico' }, ]; // ✅ Find first object that matches condition const found = arr.find((obj) => { return obj.id === 1; }); // 👇️ {id: 1, country: 'Mexico'} console.log(found); // ✅ Find multiple objects that satisfy condition const filtered = arr.filter((obj) => { return obj.country === 'Mexico'; }); // 👇️ [{id: 1, country: 'Mexico'}, {id: 3, country: 'Mexico'}] console.log(filtered);

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

在每次迭代中,我们检查id对象的属性是否等于1

如果条件返回true,则该find()方法返回相应的对象并短路。

当您只需要获取第一个符合特定条件的对象时,这非常方便。

没有浪费的迭代,因为一旦满足条件,方法就会短路并返回对象。 find()

如果我们传递给该find方法的回调函数从未返回truthy
值,则该
find方法返回undefined

索引.ts
const arr = [ { id: 1, country: 'Mexico' }, { id: 2, country: 'Germany' }, { id: 3, country: 'Mexico' }, ]; // 👇️ const found: {id: number; country: string; } | undefined const found = arr.find((obj) => { return obj.id === 1; });

请注意,found变量的类型是对象或undefined.

您可以使用
类型保护来缩小类型并能够访问对象的属性。

索引.ts
const arr = [ { id: 1, country: 'Mexico' }, { id: 2, country: 'Germany' }, { id: 3, country: 'Mexico' }, ]; // ✅ Find first object that matches condition // 👇️ const found: {id: number; country: string; } | undefined const found = arr.find((obj) => { return obj.id === 1; }); if (found) { // ✅ TypeScript now knows that found is object // and not undefined console.log(found.country); }

TypeScript can safely infer the type of the found variable to be an object in
the if block.

Use the filter() method to find multiple objects in an array that satisfy a
condition. The filter method takes a function as a parameter and returns an
array containing only the elements that satisfy the specific condition.

index.ts
const arr = [ { id: 1, country: 'Mexico' }, { id: 2, country: 'Germany' }, { id: 3, country: 'Mexico' }, ]; // ✅ Find multiple objects that satisfy condition const filtered = arr.filter((obj) => { return obj.country === 'Mexico'; }); // 👇️ [{id: 1, country: 'Mexico'}, {id: 3, country: 'Mexico'}] console.log(filtered);

The function we passed to the
Array.filter
method gets invoked with every element in the array.

If the function returns a truthy value, the element gets added to the array that the filter method returns.

Note that the filter method will iterate over the entire array, regardless of
how many times the condition is met.

This way, we are able to get multiple objects that satisfy a specific condition from an array of objects.

换句话说,我们过滤数组以仅包含满足条件的对象。

如果我们传递给该filter方法的回调函数从未返回真值,则该filter方法返回一个空数组。