Object Utility Library

raw JSON →
5.2.4 verified Sat Apr 25 auth: no javascript

object-lib is a utility library for JavaScript that provides a collection of functions for robust object manipulation, particularly focusing on recursive operations, alignment, cloning, deep comparison, and merging. The current stable version is 5.2.4, with frequent patch and minor releases, indicating active maintenance and continuous development. Key differentiators include its integration with `object-scan` syntax for declarative pathing in functions like `clone` and `Merge`, enabling powerful and flexible data transformations. It also offers unique features like `jsonSmartParse` for gracefully handling malformed JSON, often encountered from LLM outputs, and `SafeProxy` for creating proxy objects that enforce strict property access, throwing errors for non-existent keys instead of returning `undefined`. The library is designed for modern Node.js environments, requiring Node.js version 20 or higher since v5.0.0, ensuring compatibility with contemporary JavaScript features.

error ERR_REQUIRE_ESM
cause Attempting to use `require()` to import `object-lib` in a CommonJS module after v5.0.0.
fix
Migrate your module to ESM by using import statements and ensuring your package.json specifies "type": "module" or files end with .mjs.
error TypeError: Cannot read properties of undefined (reading 'someProp')
cause Accessing a non-existent nested property on an object wrapped with `SafeProxy`.
fix
Ensure all accessed properties exist on the SafeProxy object, or wrap access in try...catch blocks, or use Reflect.has() to check for property existence before attempting to read it.
error Error: Node.js version 18.x.x is not supported. Please upgrade to Node.js 20 or higher.
cause Running `object-lib` v5.x or higher in a Node.js environment older than version 20.
fix
Upgrade your Node.js installation to version 20 or a newer compatible version.
breaking Version 5.0.0 of object-lib bumped the minimum required Node.js version to 20. Projects running on older Node.js environments will encounter runtime errors or will be unable to install the package.
fix Upgrade your Node.js environment to version 20 or higher. For projects that cannot upgrade Node.js, consider staying on `object-lib` v4.x.
gotcha The `SafeProxy` function fundamentally alters JavaScript's default behavior for property access. Instead of returning `undefined` for non-existent properties, it throws a `ReferenceError`. This can be unexpected and requires careful error handling or pre-flight checks if you frequently deal with optional properties.
fix Ensure all property accesses on `SafeProxy` objects are valid or wrapped in `try...catch` blocks. Alternatively, use `Reflect.has()` or `in` operator to check for property existence before access.
gotcha The `Merge` function's behavior is heavily configured by the `logic` object, which uses `object-scan` syntax. Misunderstanding or misconfiguring this logic can lead to unintended merging outcomes, data loss, or unexpected array concatenations instead of unique item merging.
fix Thoroughly review the `object-scan` documentation and test your `Merge` configurations with diverse data sets to ensure the desired merging logic is applied correctly.
gotcha The `jsonSmartParse` function is designed to be lenient with invalid JSON, commonly found in LLM outputs. While useful, relying on it for strict JSON parsing could mask underlying data format issues or allow malformed data to be processed if strict validation is required.
fix For inputs where strict JSON adherence is critical, use `JSON.parse` with appropriate error handling. Use `jsonSmartParse` only when expecting and needing to recover from common JSON formatting errors.
npm install object-lib
yarn add object-lib
pnpm add object-lib

This quickstart demonstrates key features including object alignment, deep cloning with selective referencing, smart merging based on identifiers, using `SafeProxy` for strict property access, and parsing malformed JSON with `jsonSmartParse`.

import { align, clone, Merge, SafeProxy, jsonSmartParse } from 'object-lib';

// Align object keys to a reference object
const objToAlign = { k1: 1, k3: 3, k2: 2 };
const ref = { k2: null, k1: null, k4: 4 };
const aligned = align(objToAlign, ref);
console.log('Aligned object:', aligned); 
// Expected: { k2: 2, k1: 1 }

// Deep clone with selective referencing/exclusion using object-scan syntax
const originalData = { a: { nested: 1 }, b: { nested: 2 }, c: { nested: 3 } };
const clonedData = clone(originalData, ['b', '!c']);
console.log('Cloned data:', clonedData);
console.log('Is `a` deep cloned?', clonedData.a !== originalData.a); 
// Expected: true
console.log('Is `b` referenced?', clonedData.b === originalData.b); 
// Expected: true

// Smartly merge objects based on a unique identifier (e.g., 'id')
const merged = Merge({ '**[*]': 'id' })(
  { items: [{ id: 1, val: 'a' }, { id: 2, val: 'b' }] },
  { items: [{ id: 2, val: 'c' }, { id: 3, val: 'd' }] }
);
console.log('Merged items:', merged); 
// Expected: { items: [{ id: 1, val: 'a' }, { id: 2, val: 'c' }, { id: 3, val: 'd' }] }

// Create a SafeProxy for strict property access, throwing errors for non-existent keys
const config = SafeProxy({ db: { host: 'localhost' } });
try {
  console.log('DB Host:', config.db.host);
  // Attempting to access a non-existent property will throw
  // console.log('Non-existent property:', config.db.port);
} catch (e) {
  console.error('Caught error from SafeProxy:', e.message);
}

// Parse potentially invalid JSON strings (e.g., from LLMs)
const brokenJson = "{ name: 'Alice', age: 30, city: 'New York' }"; // Missing quotes on keys
const parsed = jsonSmartParse(brokenJson);
console.log('Smart parsed JSON:', parsed); 
// Expected: { name: 'Alice', age: 30, city: 'New York' }