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.
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.
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.
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.
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.