Collect.js only() Method
Last Updated :
30 Nov, 2020
The only() method is used to return the items from the given collection with the specified keys. It takes the key as a parameter and returns the item mapped with that key.
Syntax:
collect(array).only(key)
Parameters: The collect() method takes one argument that is converted into the collection and then only the () method is applied to it. The only() method holds the key as a parameter.
Return Value: This method returns the items from the given collection with the specified keys.
Module Installation: Install collect.js module using the following command from the root directory of your project:
npm install collect.js
The below example illustrates the only() method in collect.js:
Example 1: Filename: index.js
Javascript
const collect = require( 'collect.js' );
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const collection = collect(arr);
const only_val = collection.only([2, 5, 25]);
console.log(only_val.all());
|
Run the index.js file using the following command:
node index.js
Output:
[ 2, 5 ]
Example 2: Filename: index.js
Javascript
const collect = require( 'collect.js' );
const collection = collect({
name: 'Rahul' ,
dob: '25-10-96' ,
section: 'A' ,
score: 98,
});
const only_val = collection.only([ 'name' , 'dob' ]);
console.log(only_val.all());
|
Run the index.js file using the following command:
node index.js
Output:
{ name: 'Rahul', dob: '25-10-96' }
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...