Open In App

Lodash _.zipObject() Method

Improve
Improve
Like Article
Like
Save
Share
Report

Lodash _.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:

  • [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: In this example, we are getting an object by passing two arrays in the _.zipObject() method.

Javascript




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


Output: 

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

Example 2:  In this example, we are getting an object by passing two arrays in the _.zipObject() method.

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: In this example, 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: In this example, 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
 



Last Updated : 25 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads