The keyBy() method is used to keys the collection elements by the given key. If the collection contains multiple items with same key then the last element will appear.
Syntax:
collect(array).keyBy(key)
Parameters: The collect() method takes one argument that is converted into the collection and then keyBy() method is applied on it. The keyBy() method holds the key value.
Return Value: This method returns the collection elements by given key value.
Below example illustrate the keyBy() method in collect.js:
Example 1:
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());
Output:
{
Rahul: { name: 'Rahul', score: 98 },
Aditya: { name: 'Aditya', score: 96 },
Abhishek: { name: 'Abhishek', score: 80 }
}
Example 2:
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());
Output:
{
'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
}
}