Open In App

Collect.js only() Method

Last Updated : 30 Nov, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Requiring the module
const collect = require('collect.js');
  
// Sample values array
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  
// Creating collection object
const collection = collect(arr);
  
// Function call
const only_val = collection.only([2, 5, 25]);
  
// Printing the values
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




// Requiring the module
const collect = require('collect.js');
  
// Creating collection object
const collection = collect({
    name: 'Rahul',
    dob: '25-10-96',
    section: 'A',
    score: 98,
});
  
// Function call
const only_val = collection.only(['name', 'dob']);
  
// Printing the values
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
Previous
Next
Share your thoughts in the comments

Similar Reads