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:
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()); |
Output:
{
Rahul: { name: 'Rahul', score: 98 },
Aditya: { name: 'Aditya', score: 96 },
Abhishek: { name: 'Abhishek', score: 80 }
}
Example 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()); |
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
}
}

… [Trackback]
[…] Read More Information here on that Topic: geeksforgeeks.org/collect-js-keyby-method/ […]