Tuesday, July 31, 2018

Learn Lodash in Nodejs with examples

Lodash Nodejs Require usage with example

We already covered some basics of lodash library in front-end applications. The below posts cover the basic usage in Client-side applications

1. Learn Lodash basics with examples
2. Import Lodash in Angular applications
This article walks through the how we can use lodash in backend application using nodejs Nodejs environment has node package manager tool which is prerequisite before start using. Please make sure that npm --version command works as below. We are using npm version of 5.6.0
$npm --version
create a node application The basic node application can be created using 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 below
  "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 which contains the name of the project, version and description, script entry file and test classes information main is entry file which is 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 node file command Next step is to install lodash in nodejs project using npm install --save lodash. The following entry added in package.json
"dependencies": {
    "lodash": "^4.17.10"

Create an index.js file with below code. Basically, this is a simple example to return first four elements of a numeric array.
var numberArray = [ 7, 9, 3, 6 ,1 ];
_.first(numberArray, 4);
// returns [7,9,3]
We are using first() function and called with underscore _. As _ is a global object for this library. which is not defined. Let us see what will happens 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 run the project using node index.js
B:\lodashexamples>node index.js
_.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

got ReferenceError: _ is not defined error, This fix is an usage of require function in 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 require 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 this functions, use require('lodash').functionname
var _=require('lodash');
var numberArray = [ 7, 9, 3, 6 ,1 ];
_.first(numberArray, 4);
// returns [7,9,3]

Clone Example usage

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 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 which 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 example

In the below example, first did deep copy using cloneDeep() function, Next modified original object, Clone object will not have this 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 used is isEqual method This compares the first array with the second array and exclude 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]


Note: Only a member of this blog may post a comment.