Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptLodash _.zipObject() Method

Lodash _.zipObject() Method

The _.zipObject() method is used to combine two arrays into an object one array as keys and the other as values.

Syntax: 

_.zipObject([props=[]], [values=[]])

Parameters: This method accepts two parameters as mentioned above and described below:  

  • [props=[]](array): This parameter holds the property identifiers.
  • [values=[]](array): This parameter holds the property values.

Return Value: This method returns an object containing key values corresponding to the given array.

Example 1:  

Javascript




const _ = require('lodash');
  
let x = ['a', 'b', 'c'];
  
let y = [1, 2, 3]
  
let obj = _.zipObject(x, y)
  
console.log(obj);


Here, const _ = require(‘lodash’) is used to import the lodash library into the file.
Output: 

{ a: 1, b: 2, c: 3 }

Example 2: 

Javascript




const _ = require('lodash');
  
let x = ['name', ';language', 'used'];
  
let y = ['lodash', 'JavaScript', 'nodejs']
  
let obj = _.zipObject(x, y)
  
console.log(obj);


Output: 

{ name: 'lodash', ';language': 'JavaScript', used: 'nodejs' }

Example 3: If you pass an extra key and no values for it, it will put undefined value associated with that key. 

Javascript




const _ = require('lodash');
  
let x = ['a', 'b', 'c', 'd'];
  
let y = [1, 2, 3]
  
let obj = _.zipObject(x, y)
  
console.log(obj);


Output: 

{ a: 1, b: 2, c: 3, d: undefined }

Example 4: If you pass an extra value and no key for it, it will ignore that value. 

Javascript




const _ = require('lodash');
  
let x = ['a', 'b', 'c'];
  
let y = [1, 2, 3, 4]
  
let obj = _.zipObject(x, y)
  
console.log(obj);


Output: 

{ a: 1, b: 2, c: 3 }

Note: This will not work in normal JavaScript because it requires the library lodash to be installed.
Reference: https://lodash.com/docs/4.17.15#zipObject
 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments