在 TypeScript 中查找数组中的对象
How to find an Object in an Array in TypeScript
要在数组中查找对象:
- 调用
find()
数组上的方法,向其传递一个函数。 - 该函数应返回对相关属性的相等性检查。
- 该
find()
方法返回数组中满足条件的第一个值。
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
。
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
.
您可以使用
类型保护来缩小类型并能够访问对象的属性。
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.
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.
filter
method returns.Note that the filter
method will iterate over the entire array, regardless of
how many times the condition is met.
换句话说,我们过滤数组以仅包含满足条件的对象。
如果我们传递给该filter
方法的回调函数从未返回真值,则该filter
方法返回一个空数组。