Collect.js keyBy() 方法
keyBy() 方法用于通过给定键对集合元素进行键控。如果集合包含具有相同键的多个项目,则将出现最后一个元素。
句法:
collect(array).keyBy(key)
参数: collect() 方法接受一个参数,该参数转换为集合,然后对其应用 keyBy() 方法。 keyBy() 方法保存键值。
返回值:该方法通过给定的键值返回集合元素。
下面的示例说明了 collect.js 中的 keyBy() 方法:
示例 1:
Javascript
const collect = require('collect.js');
let obj = [
{
name: 'Rahul',
score: 98,
},
{
name: 'Aditya',
score: 96,
},
{
name: 'Abhishek',
score: 80
}
];
const collection = collect(obj);
const key_val = collection.keyBy('name');
console.log(key_val.all());
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);
const key_val = collection.keyBy('dob');
console.log(key_val.all());
输出:
{
Rahul: { name: 'Rahul', score: 98 },
Aditya: { name: 'Aditya', score: 96 },
Abhishek: { name: 'Abhishek', score: 80 }
}
示例 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);
const key_val = collection.keyBy('dob');
console.log(key_val.all());
输出:
{
'25-10-96': {
name: 'Aditya', dob: '25-10-96',
section: 'B', score: 96
},
'16-08-94': {
name: 'Abhishek', dob: '16-08-94',
section: 'A', score: 80
},
'19-08-96': {
name: 'Rahul', dob: '19-08-96',
section: 'B', score: 77
}
}