@js-utility/object
Version:
Comprehensive utility library for advanced object manipulation in JavaScript: deep get/set, clone, merge, flatten, and more. Ideal for Node.js and browser projects as a lightweight lodash alternative.
322 lines (210 loc) β’ 8.3 kB
Markdown
# Object Utils JS
A powerful and flexible library for advanced object manipulation in JavaScript and TypeScript. `@js-utility/object` provides utilities for deep extraction, picking, omitting, merging, and setting properties in objects, along with other helpful functions. Designed for developers who need precise control over nested data structures.
If this package has been helpful to you, your support goes a long way in helping maintain it, improve its features, and build more open-source tools like it.
[Buy Me a Coffee β](https://buymeacoffee.com/pradip_sabhadiya)
## Features
- **Deep Extraction**: Extract deeply nested values with support for wildcards and references.
- **Deep Picking**: Pick specific properties from objects or arrays, even at nested levels.
- **Deep Omitting**: Remove specific properties from objects or arrays, including nested ones.
- **Deep Setting**: Assign values to deeply nested paths, creating intermediate structures as needed.
- **Object Merging**: Merge objects deeply with support for arrays, functions, and special cases.
- **Validation**: Check if a value is not null or undefined.
- **Utility Functions**: Clone objects deeply, parse paths, and more.
## Installation
Install the library using npm or yarn:
```bash
npm install @js-utility/object
# or
yarn add @js-utility/object
```
## API & Usage
### 1. `deepExtract`
Extracts a deeply nested value from an object using a dot/bracket path.
```typescript
import { deepExtract } from '@js-utility/object';
const data = { a: { b: { c: 42 } } };
console.log(deepExtract(data, 'a.b.c')); // 42
console.log(deepExtract(data, 'a.b.d', { default: 'Not Found' })); // 'Not Found'
```
### 2. `pickDeep`
Picks specific properties from an object or array, supporting wildcards.
```typescript
import { pickDeep } from '@js-utility/object';
const data = { a: { b: { c: 1, d: 2 } }, e: [{ f: 3 }, { f: 4 }] };
console.log(pickDeep(data, ['a.b.c', 'e[*].f']));
// { a: { b: { c: 1 } }, e: [{ f: 3 }, { f: 4 }] }
```
### 3. `deepOmit`
Omits specific properties from an object or array, including nested ones.
```typescript
import { deepOmit } from '@js-utility/object';
const data = { a: { b: { c: 1, d: 2 } }, e: [{ f: 3 }, { g: 4 }] };
console.log(deepOmit(data, ['a.b.c', 'e[1].g']));
// { a: { b: { d: 2 } }, e: [{ f: 3 }, {}] }
```
### 4. `setDeep`
Assigns a value to a deeply nested path, creating intermediate structures as needed.
```typescript
import { setDeep } from '@js-utility/object';
const data = {};
setDeep(data, 'a.b.c', 42);
console.log(data); // { a: { b: { c: 42 } } }
```
### 5. `mergeObjs`
Merges multiple objects deeply, handling arrays, functions, and special cases.
```typescript
import { mergeObjs } from '@js-utility/object';
const obj1 = { a: { b: 1 } };
const obj2 = { a: { c: 2 } };
console.log(mergeObjs(obj1, obj2));
// { a: { b: 1, c: 2 } }
```
### 6. `isNotNull`
Checks if a value is not null or undefined.
```typescript
import { isNotNull } from '@js-utility/object';
console.log(isNotNull(null)); // false
console.log(isNotNull({})); // false
console.log(isNotNull({ key: 'value' })); // true
```
### 7. `cloneDeep`
Clones an object deeply.
```typescript
import { cloneDeep } from '@js-utility/object';
const obj = { a: { b: 1 } };
const cloned = cloneDeep(obj);
console.log(cloned); // { a: { b: 1 } }
```
### 8. `parsePath`
Parses a dot/bracket notation path into an array of keys.
```typescript
import { parsePath } from '@js-utility/object';
console.log(parsePath('a.b[0].c')); // ['a', 'b', 0, 'c']
```
### 9. `hasProperty`
Checks if an object has a specific property.
```typescript
import { hasProperty } from '@js-utility/object';
const obj = { a: 1 };
console.log(hasProperty(obj, 'a')); // true
console.log(hasProperty(obj, 'b')); // false
```
### 10. `toNestedJson`
Converts an array of dot-separated strings into a nested JSON object.
```typescript
import { toNestedJson } from '@js-utility/object';
const input = ['a.b.c', 'a.b.d', 'e'];
console.log(toNestedJson(input));
// { a: { b: { c: 1, d: 1 } }, e: 1 }
```
### 11. `fromNestedJson`
Converts a nested JSON object into an array of dot-separated strings.
```typescript
import { fromNestedJson } from '@js-utility/object';
const input = { a: { b: { c: 1, d: 1 } }, e: 1 };
console.log(fromNestedJson(input));
// ['a.b.c', 'a.b.d', 'e']
```
### 12. `removeDuplicates` / `union`
Removes duplicate values from an array (deep equality). `union` is an alias.
```typescript
import { removeDuplicates, union } from '@js-utility/object';
const arr = [{ a: 1 }, { a: 1 }, { a: 2 }];
console.log(removeDuplicates(arr)); // [ { a: 1 }, { a: 2 } ]
console.log(union(arr)); // [ { a: 1 }, { a: 2 } ]
```
### 13. `arrayEquals`
Deeply compares two arrays for equality.
```typescript
import { arrayEquals } from '@js-utility/object';
console.log(arrayEquals([1, 2], [1, 2])); // true
console.log(arrayEquals([1, 2], [2, 1])); // false
```
### 14. `intersect`
Returns the intersection of two arrays (deep equality).
```typescript
import { intersect } from '@js-utility/object';
console.log(intersect([1, 2, 3], [2, 3, 4])); // [2, 3]
console.log(intersect([{ a: 1 }], [{ a: 1 }, { a: 2 }])); // [ { a: 1 } ]
```
### 15. `sort`
Sorts an array of objects based on multiple criteria, with optional prefix prioritization for string fields.
```typescript
import { sort } from '@js-utility/object';
const data = [
{ name: 'apple', rank: 2 },
{ name: 'banana', rank: 1 },
{ name: 'apricot', rank: 1 },
];
const sorted = sort(data, [
{ key: 'name', order: 1, priority_prefix: 'ap' },
{ key: 'rank', order: -1 }
]);
console.log(sorted);
// [ { name: 'apricot', rank: 1 }, { name: 'apple', rank: 2 }, { name: 'banana', rank: 1 } ]
```
### 16. `groupBy`
Groups an array of objects by a specified key (supports deep paths).
```typescript
import { groupBy } from '@js-utility/object';
const users = [
{ id: 1, info: { role: 'admin' } },
{ id: 2, info: { role: 'user' } },
{ id: 3, info: { role: 'admin' } }
];
const grouped = groupBy(users, 'info.role');
console.log(grouped);
// { admin: [ {...}, {...} ], user: [ {...} ] }
```
## Advanced Examples
### Handling Wildcards
```typescript
const data = { users: [{ id: 1 }, { id: 2 }] };
console.log(pickDeep(data, ['users[*].id']));
// { users: [{ id: 1 }, { id: 2 }] }
```
### Circular References
```typescript
const obj = { a: {} };
obj.a.b = obj.a;
console.log(deepExtract(obj, 'a.b', { maxRefVisits: 1 })); // undefined
```
## π TypeScript Support
This package is built with full TypeScript support. All functions are type-safe, and type definitions are bundled, so you get autocomplete, inline documentation, and compile-time safety out of the box, no need to install `@types`.
## π§ͺ Testing
This package is thoroughly tested using Jest, with a focus on correctness, edge cases, and null-safety.
## π€ Contributing
This project is maintained privately. While direct contributions (e.g., pull requests or code changes) are not open to the public, **feedback, suggestions, and issue reports are always welcome.**
If you notice any bugs, edge cases, or have ideas for improvement, feel free to reach out or open an issue (if access is available). Your input helps make the package more robust and useful for everyone!
## π Support / Donate
If you find this package useful, consider supporting its development. Your support helps maintain the project, improve documentation, and add new features.
Support as through :
- [Buy Me a Coffee β](https://buymeacoffee.com/pradip_sabhadiya)
- [GitHub](https://github.com/sponsors/AIWebBuilder)
## π¬ Support & Feedback
Have ideas, suggestions, or found a bug? I'd love to hear from you!
- **Feedback**: Whether itβs a feature request or an edge case you'd like handled, your input helps improve the package.
- **Issues**: If you run into a bug or unexpected behavior, feel free to open an issue (if the repo is accessible).
- **Reach Out**: You can also reach out directly for feedback or discussion via email or the contact details in the repository.
Your feedback helps shape better tools for everyone using this package.