How to add Lodash in Nodejs with examples?

We’ve already covered some of the basics of the Lodash library in front-end applications.

You can check other posts that cover the basic usage in Client-side applications

This article walks through how we can use lodash in backend applications such as nodejs. The node package management tool comes standard with the Nodejs environment, and it’s a need before you start using it.

Please make sure that the npm —version command works as below. We are using the npm version of 7.11.1

$npm --version  
7.11.1

First, create a node application The basic node application can be created using the npm init command

$npm init

This command asks the user to enter other details like package name version description and entry point.

The output of this command creates a package.json as seen

{
  "name": "lodashexamples",
  "version": "1.0.0",
  "description": "Lodash Nodejs Example",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Every project has package.json that contains the name of the project, version and description, script entry file, and test class information.

main is the entry file that is the starting point to be executed of your project when starting your using npm start command.

Here we are not starting the project this way. Another way is to use the node file command. The next step is to install lodash in the nodejs project using the below command.

npm install --save lodash

The following entry was added in package.json

"dependencies": {  
 "lodash": "^4.17.10"  
 }

Create an index.js file with the below code. This is a simple example to return the first four elements of a numeric array.

var numberArray = [7, 9, 3, 6, 1];
_.first(numberArray, 4);
// returns [7,9,3]

We are using the first() function and called with underscore(_). As _ is a global object for this library.

Let us see what will happen when executed as below.
Running nodejs using node command We are seeing a simple step to run the project. The use node index.js command to start the project Now next step is to run the project using node index.js

B:\lodashexamples>node index.js  
B:\lodashexamples\index.js:2  
\_.first(numberArray, 3);  
^

ReferenceError: \_ is not defined  
 at Object. (B:\Workspace\blog\nodejsexamples\lodashexamples\index.js:2:1)  
 at Module.\_compile (module.js:652:30)  
 at Object.Module.\_extensions..js (module.js:663:10)  
 at Module.load (module.js:565:32)  
 at tryModuleLoad (module.js:505:12)  
 at Function.Module.\_load (module.js:497:3)  
 at Function.Module.runMain (module.js:693:10)  
 at startup (bootstrap_node.js:188:16)  
 at bootstrap_node.js:609:3

The above code throws a ReferenceError: \_ is not defined error, The fix is the usage of the require function in the nodejs application.

Here _ is not available as global and the object is not declared globally.

so you need to declare this module globally or locally using the required method. Globally means you will declare at the start of the file.

Locally means you will not declare in the global scope, wherever you use these functions, use require(‘lodash’).function name

var _ = require("lodash");
var numberArray = [7, 9, 3, 6, 1];
_.first(numberArray, 4);
// returns [7,9,3]

How to clone an object in nodejs with Example

Already posted an article on Understand javascript cloning. This library provides an easy way to implement cloning. You don’t need to write a lot of code to do this. Clone offers a shallow copy mechanism.

const _ = require("lodash");
const originalData = {
  name: "Franc",
  department: {
    type: "Marketing",
  },
};
const clonedData = _.clone(originalData);
originalData.name = "Kiran";
originalData.department.type = "Development";
console.log(originalData); // returns { name: 'Kiran', department: { type: 'Development' } }
console.log(clonedData); //returns  { name: 'Franc', department: { type: 'Development' } }

using clone() method, It creates a cloned object that copies primitive values and references, but not objects themselves. Now we have changed the original data, cloned obj will have their data but not modified original data values. But both objects are referencing to same as reference data is modified.

cloneDeep nodejs example

In the below example, first did deep copy using the cloneDeep() function, Next modified original object, the Clone object will not have these modified changes.

Please see the example usage.

const cloneDeepData = _.cloneDeep(originalData);
originalData.name = "Kiran";
originalData.department.type = "Development";
console.log(originalData); // returns { name: 'Kiran', department: { type: 'Development' } }
console.log(cloneDeepData); //returns  { name: 'Franc', department: { type: 'Marketing' } }

Checking two arrays of elements/objects and returns the difference

will use differenceWith function - _.differenceWith(firstArray, [secondArray], [comparator]) First Array to consider it for checking, secondArray is to exclude Comparator here isEqual method is used. This compares the first array with the second array and excludes the values from First Array which are matched and return not matched from the first array

var _ = require("lodash");
var firstArray = [1, 5, 6, 7, 2];
var secondArray = [6, 7, 1];
console.log(_.differenceWith(firstArray, secondArray, _.isEqual)); // returns [5,2]

Conclusion

To Summarize, Learned how to integrate lodash into nodejs application. It includes basic examples of using lodash.