📜  Collect.js firstWhere() 方法

📅  最后修改于: 2022-05-13 01:56:26.515000             🧑  作者: Mango

Collect.js firstWhere() 方法

firstWhere() 方法用于返回具有给定键值对的集合中的第一个元素。它可用于通过仅指定对象中的任何键值对来查找数组中的任何元素。

句法:

collect(array).firstWhere( key, value )

参数: collect() 方法接受一个参数,该参数转换为集合,然后将 firstWhere() 方法应用于它。 firstWhere() 方法将要搜索的键值对作为参数。

返回值:它返回具有给定键值对的集合中的第一个元素。

下面的示例说明了 collect.js 中的firstWhere() 方法

示例 1:

Javascript
const collect = require("collect.js");
  
let obj = [
  {
    name: "Rahul",
    score: 98,
  },
  {
    name: "Aditya",
    score: 96,
  },
  {
    name: "Abhishek",
    score: 80,
  },
  {
    name: "Rahul",
    score: 77,
  },
];
  
const collection = collect(obj);
  
let first_Val = 
  collection.firstWhere("name", "Rahul");
console.log(first_Val);


Javascript
const collect = require("collect.js");
  
let obj = [
  {
    name: "Rahul",
    dob: "25-10-96",
    section: "A",
    score: 98,
  },
  {
    name: "Aditya",
    dob: "25-10-96",
    section: "B",
    score: 96,
  },
  {
    name: "Abhishek",
    dob: "16-08-94",
    section: "A",
    score: 80,
  },
  {
    name: "Rahul",
    dob: "19-08-96",
    section: "B",
    score: 77,
  },
];
  
const collection = collect(obj);
  
let first_Val = 
  collection.firstWhere("dob", "25-10-96");
console.log(first_Val);


输出:

{ name: 'Rahul', score: 98 }

示例 2:

Javascript

const collect = require("collect.js");
  
let obj = [
  {
    name: "Rahul",
    dob: "25-10-96",
    section: "A",
    score: 98,
  },
  {
    name: "Aditya",
    dob: "25-10-96",
    section: "B",
    score: 96,
  },
  {
    name: "Abhishek",
    dob: "16-08-94",
    section: "A",
    score: 80,
  },
  {
    name: "Rahul",
    dob: "19-08-96",
    section: "B",
    score: 77,
  },
];
  
const collection = collect(obj);
  
let first_Val = 
  collection.firstWhere("dob", "25-10-96");
console.log(first_Val);

输出:

{ name: 'Rahul', dob: '25-10-96', section: 'A', score: 98 }