Lodash - Object
Lodash - Object Methods
Section titled “Lodash - Object Methods”Lodash offers a robust suite of functions for manipulating and working with JavaScript objects. While modern JavaScript (ES6+) has introduced native methods like Object.assign, Object.keys, Object.values, and Object.entries, Lodash often provides more powerful, flexible, or convenient alternatives, especially for complex operations like deep merging, safe property access, and transforming object structures.
This section explores key Lodash methods for object manipulation, highlighting their utility and comparing them to native JavaScript features where applicable.
Core Object Methods
Section titled “Core Object Methods”Here’s a selection of frequently used Lodash object methods:
| Method & Syntax | Description & Modern JS Comparison |
|---|---|
| assign _.assign(object, [sources]) | Assigns own enumerable string keyed properties of source objects to the destination object. Sources are applied from left to right. Mutates object. Similar to Object.assign(), but Lodash doesn’t trigger setters on the destination object. |
| assignIn _.assignIn(object, [sources]) | Like _.assign, but includes inherited source properties. |
| defaults _.defaults(object, [sources]) | Assigns own enumerable string keyed properties of source objects to the destination object for all properties that are undefined on the destination. Useful for setting default options. Mutates object. |
| defaultsDeep _.defaultsDeep(object, [sources]) | Like _.defaults, but recursively assigns default properties. |
| get _.get(object, path, [defaultValue]) | Safely retrieves the value at path of object. If the path doesn’t exist, defaultValue is returned. Prevents errors from accessing nested properties on potentially null or undefined objects. Partially replaceable by Optional Chaining (?.) in modern JS, but _.get handles paths as strings or arrays robustly. |
| set _.set(object, path, value) | Sets the value at path of object. If a portion of the path doesn’t exist, it’s created. Mutates object. |
| has _.has(object, path) | Checks if path is a direct property of object. Safer than obj.hasOwnProperty(key) for objects created with Object.create(null). |
| hasIn _.hasIn(object, path) | Checks if path is an own or inherited property of object. |
| keys _.keys(object) | Creates an array of the own enumerable property names of object. Similar to Object.keys(). |
| keysIn _.keysIn(object) | Creates an array of the own and inherited enumerable property names of object. Similar to a for...in loop’s keys. |
| values _.values(object) | Creates an array of the own enumerable property values of object. Similar to Object.values(). |
| valuesIn _.valuesIn(object) | Creates an array of the own and inherited enumerable property values of object. |
| toPairs _.toPairs(object) | Creates an array of own enumerable string keyed-value pairs for object. Similar to Object.entries(). |
| toPairsIn _.toPairsIn(object) | Creates an array of own and inherited enumerable string keyed-value pairs for object. |
| merge _.merge(object, [sources]) | Recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Mutates object. Unlike Object.assign, it merges nested objects instead of overwriting them. |
| pick _.pick(object, [paths]) | Creates an object composed of the picked object properties specified by paths. |
| pickBy .pickBy(object, [predicate=.identity]) | Creates an object composed of the object properties predicate returns truthy for. |
| omit _.omit(object, [paths]) | Creates an object composed of the own and inherited enumerable property paths of object that are not omitted. |
| omitBy .omitBy(object, [predicate=.identity]) | Creates an object composed of the own and inherited enumerable property paths of object that predicate doesn’t return truthy for. |
| mapValues .mapValues(object, [iteratee=.identity]) | Creates an object with the same keys as object and values generated by running each own enumerable string keyed property of object thru iteratee. |
| findKey .findKey(object, [predicate=.identity]) | Iterates over own enumerable properties, returning the key of the first element predicate returns truthy for. |
| invert _.invert(object) | Creates an object composed of the inverted keys and values of object. If object contains duplicate values, subsequent values overwrite property assignments of previous values. |
| transform .transform(object, [iteratee=.identity], [accumulator]) | An alternative to _.reduce for objects, allowing the accumulator to be implicitly returned if the iteratee doesn’t return explicitly. Can be more concise for building up objects. |
| unset _.unset(object, path) | Removes the property at path of object. Returns true if the property is deleted, else false. Mutates object. |
Choosing Between Lodash and Native Methods
Section titled “Choosing Between Lodash and Native Methods”Consider using native JavaScript methods (Object.assign, Object.keys, etc.) for simple tasks to potentially reduce bundle size and leverage built-in engine optimizations. Opt for Lodash when you need:
- Deep operations:
_.merge,_.defaultsDeep,_.cloneDeep(from Lang module). - Safe property access:
_.get,_.result. - Advanced filtering/transformation:
_.pickBy,_.omitBy,_.mapValues,_.transform. - Convenience: Shorthand syntax for predicates in methods like
_.pickBy,_.findKey. - Consistency: Working with potentially non-standard objects (e.g.,
Object.create(null)). - Comprehensive utilities: Functions like
_.invert,_.findKey,_.defaultsdon’t have direct native equivalents.
Example: Safe Access and Defaults
Section titled “Example: Safe Access and Defaults”import _ from 'lodash-es';
const user = { name: 'Alice', address: { street: '123 Main St', // city is missing }, preferences: null};
const config = { timeout: 5000, retries: 3};
// Safely get nested propertyconst city = _.get(user, 'address.city', 'Unknown');// city is 'Unknown'// Native alternative: const city = user?.address?.city ?? 'Unknown';
// Safely get property from potentially null objectconst theme = _.get(user, 'preferences.theme', 'light');// theme is 'light'// Native alternative: const theme = user?.preferences?.theme ?? 'light';
// Set default configurationconst currentConfig = { retries: 5 };_.defaults(currentConfig, config);// currentConfig is now { retries: 5, timeout: 5000 }
console.log(`City: ${city}`);console.log(`Theme: ${theme}`);console.log('Config:', currentConfig);Explore the official Lodash documentation for detailed explanations and more examples of each object method.