Skip to content
大纲

根据对象数组的键值在数组中查找对象

语法

js
import { findObjectInArray } from 'warbler-js';
const result = findObjectInArray(arr, key, value);

参数

  • arr (Array) : 待查找的目标数组。
  • key (String) : 需要查找的对象的 key
  • value (String | number) : 需要查找的对象的 value

返回值

Array : 返回符合条件的对象组成的数组。

源码

js
const findObjectInArray = (arr, key, value) => arr.filter((obj) => obj[key] === value);

例子

js
import { findObjectInArray } from 'warbler-js';
const fruits = [
  { name: 'Bananas', quantity: 5 },
  { name: 'Apples', quantity: 10 },
  { name: 'Grapes', quantity: 2 },
  { name: 'Apples', quantity: 4 },
];
const result = findObjectInArray(fruits, 'name', 'Apples');
console.log(result);

// 输出以下内容

[
  {
    name: 'Apples',
    quantity: 10,
  },
  {
    name: 'Apples',
    quantity: 4,
  },
];

添加版本

1.2.2

Released under the MIT License.