Extend Shallow

3.0.2 · maintenance · verified Sun Apr 19

extend-shallow is a minimalist JavaScript utility designed to merge the enumerable properties of one or more source objects into a target object. It performs a *shallow* merge, meaning only top-level properties are copied; nested objects or arrays are copied by reference rather than being cloned. The current stable version is 3.0.2, last published in 2017, indicating a mature and stable, but not actively feature-developed, codebase. It primarily targets Node.js environments from version 0.10.0 upwards, supporting CommonJS module syntax. While modern JavaScript environments widely support `Object.assign()` for similar functionality, extend-shallow serves as a lightweight alternative, particularly useful in legacy environments or when a direct, unopinionated shallow merge is explicitly required without the overhead of polyfills or broader compatibility layers. Its key differentiator lies in its focused, single-purpose design, making it a very small footprint utility.

Common errors

Warnings

Install

Imports

Quickstart

Illustrates how to perform a basic shallow extension with multiple source objects and how to create a shallow clone, highlighting the reference-copy behavior for nested objects.

const extend = require('extend-shallow');

// Basic shallow extension
const targetObj = { a: 1, b: { c: 2 } };
const sourceObj1 = { b: { d: 3 }, e: 4 };
const sourceObj2 = { f: 5 };

const result = extend(targetObj, sourceObj1, sourceObj2);
console.log('Extended object:', result);
// Expected output: { a: 1, b: { d: 3 }, e: 4, f: 5 }
// Note: b from sourceObj1 overwrites b from targetObj. Nested {d:3} is copied by reference.

// Shallow clone by extending into an empty object
const original = { x: 10, y: { z: 20 } };
const clone = extend({}, original);
console.log('Shallow clone:', clone);
console.log('Is original.y === clone.y?', original.y === clone.y); // true, because it's a shallow copy

// Demonstrating the shallow copy behavior
clone.y.z = 99;
console.log('Original after modifying clone.y:', original);
// Expected: Original will also show { x: 10, y: { z: 99 } } because y is a shared reference.

view raw JSON →