JavaScript Object Utilities

2.2.1 · active · verified Sun Apr 19

js-object-utilities is a lightweight JavaScript package providing a collection of helper methods designed for working with nested objects. It simplifies common tasks like accessing, setting, deleting, and transforming deeply nested properties using dot-notation paths. Currently at version 2.2.1, the library maintains a stable release cadence. Key differentiators include its focus on handling complex object structures gracefully, providing utilities for deep equality checks, detecting circular references, and clearing empty objects, which are often overlooked in more general-purpose utility libraries. It ships with TypeScript type definitions, enhancing development experience for TypeScript users.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates `get`, `set`, `pick`, `delete`, `clearEmpties`, and `isCircular` on a nested object, including how to set up a circular reference.

import objectUtils from 'js-object-utilities';

interface MyObject {
  data: {
    hello: string;
    space?: string;
    node?: string;
    otherData?: Record<string, unknown>;
  };
  array?: { first: number };
  array2?: MyObject;
}

let myObject: MyObject = {
  data: {
    hello: 'world',
    space: 'travel',
    node: 'npm',
    otherData: {}
  }
};

console.log('Original object:', JSON.stringify(myObject, null, 2));

// Get a nested value
const helloValue = objectUtils.get(myObject, 'data.hello');
console.log(`Value of 'data.hello': ${helloValue}`); // Expected: world

// Set a nested value
objectUtils.set(myObject, 'data.hello', 'universe');
console.log('After setting data.hello:', JSON.stringify(myObject, null, 2)); // Expected: universe

// Pick specific keys to create a new object
const pickedObject = objectUtils.pick(myObject, ['data.hello', 'data.space']);
console.log('Picked object:', JSON.stringify(pickedObject, null, 2)); // Expected: { "data": { "hello": "universe", "space": "travel" } }

// Delete a nested key
objectUtils.delete(myObject, 'data.node');
console.log('After deleting data.node:', JSON.stringify(myObject, null, 2));

// Clear empty objects
objectUtils.clearEmpties(myObject);
console.log('After clearing empties:', JSON.stringify(myObject, null, 2)); // 'otherData' should be removed

// Check for circularity
let circularObject: MyObject = {
  data: { hello: 'circular' }
};
circularObject.array2 = circularObject; // Create circular reference
console.log('Is circular object circular?', objectUtils.isCircular(circularObject)); // Expected: true

view raw JSON →