The lodash method _.defaults exported as a module for assigning default object properties.
npx @tessl/cli install tessl/npm-lodash--defaults@4.2.0The lodash method _.defaults exported as a standalone module. This utility function fills in undefined properties in an object with the first value present in a list of defaults objects, providing a safe way to assign default values without overwriting existing meaningful data.
npm install lodash.defaultsconst defaults = require("lodash.defaults");For ES6+ environments:
import defaults from "lodash.defaults";const defaults = require("lodash.defaults");
// Basic property defaulting
const result = defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
// => { 'user': 'barney', 'age': 36 }
// Null vs undefined handling
const withNull = defaults({ 'a': null }, { 'a': 1 });
// => { 'a': null } (null is preserved)
const withUndefined = defaults({ 'a': undefined }, { 'a': 1 });
// => { 'a': 1 } (undefined is filled)
// Multiple source objects
const multiple = defaults(
{ name: 'Alice' },
{ name: 'Bob', age: 25 },
{ age: 30, city: 'NYC' }
);
// => { name: 'Alice', age: 25, city: 'NYC' }Assigns default values to undefined properties in objects, with support for multiple source objects and prototype-aware property handling.
/**
* Assigns own and inherited enumerable properties of source objects to the
* destination object for all destination properties that resolve to `undefined`.
* Source objects are applied from left to right. Once a property is set,
* additional values of the same property are ignored.
*
* Note: This method mutates `object`.
*
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
*/
function defaults(object, ...sources);Key Behaviors:
object parameter is modified and returnedundefined in the destinationnull is treated as a valid value and won't be overwrittenUsage Examples:
const defaults = require("lodash.defaults");
// Configuration object with defaults
const config = defaults(
userOptions,
{ timeout: 5000, retries: 3, verbose: false }
);
// API parameter defaulting
function processUser(userData) {
return defaults(userData, {
active: true,
role: 'user',
preferences: {}
});
}
// Prototype property handling
const obj = Object.create({ inherited: 'parent' });
obj.own = 'child';
defaults(obj, { inherited: 'default', new: 'value' });
// obj.inherited remains 'parent' (not overwritten)
// obj.new becomes 'value' (filled in)
// Handling constructor and other prototype properties
const target = {};
defaults(target, { constructor: MyConstructor, toString: customToString });
// Fills in constructor and toString if they're undefined on targetCommon Use Cases:
Important Notes: