Lodash zipObject with More Keys Than Values

When using the Lodash _.zipObject method with an array of keys that is longer than the array of values, Lodash still creates properties for all provided keys and assigns undefined to any key that lacks a corresponding value. This article explains how this behavior works in JavaScript, illustrates it with clear code examples, and details the practical implications of keys receiving undefined values.

How Lodash Handles Mismatched Arrays

The _.zipObject function takes two arrays: an array of property identifiers (keys) and an array of values. It pairs each key with the value located at the same index.

When the keys array contains more elements than the values array, JavaScript index lookups on the values array for out-of-bounds indices return undefined. Lodash assigns that result directly to the target key.

const _ = require('lodash');

const keys = ['id', 'username', 'email', 'isActive'];
const values = [101, 'jdoe'];

const user = _.zipObject(keys, values);

console.log(user);
// Output:
// { id: 101, username: 'jdoe', email: undefined, isActive: undefined }

Key Existence vs. Missing Properties

A key with an undefined value is not the same as an omitted key. The resulting object explicitly contains the extra properties:

  1. in operator and hasOwnProperty: Checking for property presence returns true.
    console.log('email' in user); // true
    console.log(user.hasOwnProperty('email')); // true
  2. Key Enumeration: Methods like Object.keys() will include keys mapped to undefined.
    console.log(Object.keys(user)); // ['id', 'username', 'email', 'isActive']
  3. JSON Serialization: Passing the object to JSON.stringify() removes properties whose values are undefined.
    console.log(JSON.stringify(user)); 
    // Output: '{"id":101,"username":"jdoe"}'

How to Avoid undefined Values

If you do not want unpaired keys to appear in the resulting object, you can slice the keys array to match the values length before passing them to _.zipObject:

const safeKeys = keys.slice(0, values.length);
const compactObject = _.zipObject(safeKeys, values);

console.log(compactObject);
// Output: { id: 101, username: 'jdoe' }

Alternatively, you can clean the object after creation using Lodash's _.pickBy:

const cleanedObject = _.pickBy(user, value => value !== undefined);

console.log(cleanedObject);
// Output: { id: 101, username: 'jdoe' }