TypeScript 中按属性值查找数组中的对象

TypeScript 中要按属性值在数组中查找对象:

  1. 在数组上调用 find() 方法。
  2. 在每次迭代中,检查值是否满足条件。
  3. find() 方法返回数组中满足条件的第一个值。
const arr = [
  { id: 1, language: 'typescript' },
  { id: 2, language: 'javascript' },
  { id: 3, language: 'typescript' },
];

// ✅ Find first object whose value matches condition
const first = arr.find((obj) => {
  return obj.id === 2;
});

// 👇️ {id: 2, language: 'javascript'}
console.log(first);

// ✅ Find multiple objects whose values satisfy condition
const all = arr.filter((obj) => {
  return obj.language === 'typescript';
});

// 👇️ [{id: 1, language: 'typescript'}, {id: 3, language: 'typescript'}]
console.log(all);

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

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

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

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

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

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

const arr = [
  { id: 1, language: 'typescript' },
  { id: 2, language: 'javascript' },
  { id: 3, language: 'typescript' },
];

// 👇️ const first: {id: number; language: string;} | undefined
const first = arr.find((obj) => {
  return obj.id === 2;
});

请注意 ,first 变量的类型是对象或 undefined 。

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

const arr = [
  { id: 1, language: 'typescript' },
  { id: 2, language: 'javascript' },
  { id: 3, language: 'typescript' },
];

// 👇️ const first: {id: number; language: string;} | undefined
const first = arr.find((obj) => {
  return obj.id === 2;
});

if (first) {
  // ✅ first is inferred to be object
  console.log(first.language);
}

TypeScript 可以安全地将第一个变量的类型推断为 if 块中的对象。

使用 filter() 方法在数组中查找具有满足条件的值的多个对象。 filter() 方法接受一个函数作为参数,返回一个只包含满足特定条件的元素的数组。

const arr = [
  { id: 1, language: 'typescript' },
  { id: 2, language: 'javascript' },
  { id: 3, language: 'typescript' },
];

// ✅ Find multiple objects whose values satisfy condition
const all = arr.filter((obj) => {
  return obj.language === 'typescript';
});

// 👇️ [{id: 1, language: 'typescript'}, {id: 3, language: 'typescript'}]
console.log(all);

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

如果该函数返回真值,则该元素将添加到过滤器方法返回的数组中。

请注意 ,无论条件满足多少次,过滤方法都会遍历整个数组。

这样,我们就可以从对象数组中获取满足条件的多个对象。

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

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