当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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);

输出:

{ 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 }

相关用法


注:本文由纯净天空筛选整理自AshokJaiswal大神的英文原创作品 Collect.js firstWhere() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。