Lightweight utility function for merging JavaScript objects with shallow property copying
npx @tessl/cli install tessl/npm-utils-merge@1.0.0Utils Merge is a lightweight utility library that provides a simple merge() function for merging JavaScript objects. The function copies all enumerable properties from a source object into a destination object, modifying the destination object in place with shallow copying behavior.
npm install utils-mergeconst merge = require('utils-merge');For ES modules:
import merge from 'utils-merge';const merge = require('utils-merge');
// Basic object merging
const a = { foo: 'bar' };
const b = { bar: 'baz' };
merge(a, b);
console.log(a); // { foo: 'bar', bar: 'baz' }
// Property overwriting
const config = { host: 'localhost', port: 3000 };
const userConfig = { port: 8080, ssl: true };
merge(config, userConfig);
console.log(config); // { host: 'localhost', port: 8080, ssl: true }Merges properties from a source object into a destination object with shallow copying.
/**
* Merge object b with object a.
* Copies all enumerable properties from source object into destination object.
* Modifies the destination object in place and returns it.
*
* @param {Object|null|undefined} a - Destination object that will be modified
* @param {Object|null|undefined} b - Source object whose properties will be copied
* @return {Object|null|undefined} - Returns the modified destination object (or a if null/undefined)
*/
function merge(a, b);Behavior:
a in placeb overwrite existing properties in destination object aab is undefined or null, destination object a is returned unchangeda is undefined or null, it is returned as-isUsage Examples:
const merge = require('utils-merge');
// Simple merging
const target = { name: 'Alice' };
const source = { age: 25, city: 'Boston' };
const result = merge(target, source);
// target is now { name: 'Alice', age: 25, city: 'Boston' }
// result === target (same reference)
// Property overwriting
const defaults = { timeout: 5000, retries: 3 };
const options = { timeout: 10000 };
merge(defaults, options);
// defaults is now { timeout: 10000, retries: 3 }
// Handling undefined source
const obj = { foo: 'bar' };
merge(obj, undefined);
// obj remains { foo: 'bar' }
// Configuration merging pattern
function createClient(userOptions = {}) {
const defaultOptions = {
host: 'api.example.com',
port: 443,
timeout: 5000,
retries: 3
};
return merge(defaultOptions, userOptions);
}
const client = createClient({ port: 8080, ssl: false });
// Returns: { host: 'api.example.com', port: 8080, timeout: 5000, retries: 3, ssl: false }