lodash-id: ID-based Resource Manipulation for Lodash/Lowdb

0.14.1 · active · verified Wed Apr 22

lodash-id is a utility package that extends Lodash and Underscore with methods for manipulating collections of JavaScript objects based on a unique `id` property, effectively turning them into simple in-memory databases. It provides a set of CRUD-like operations such as `getById`, `insert`, `upsert`, `updateById`, `removeById`, and `removeWhere`. The package normalizes ID comparisons, allowing both string and integer IDs to be treated equivalently since version `0.12.0`. The current stable version is `0.14.1`. Releases are infrequent but address compatibility and feature refinements. Its primary differentiator is its integration as a Lodash mixin, simplifying common data management patterns within existing Lodash-based applications or in conjunction with `lowdb`. It does not handle data persistence directly since `v0.14.0`, delegating that responsibility to `lowdb` or custom implementations.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to initialize lodash-id and perform basic CRUD operations like insert, get, update, upsert, and remove on an in-memory collection.

const _ = require('lodash');
_.mixin(require('lodash-id'));

const db = {
  posts: [
    { id: 1, title: 'First Post', published: false },
    { id: 2, title: 'Second Post', published: true }
  ]
};

// Insert a new document
const newPost = _.insert(db.posts, { title: 'Third Post' });
console.log('Inserted post:', newPost); // { id: 3, title: 'Third Post' }

// Get a document by ID
const post1 = _.getById(db.posts, 1);
console.log('Got post by ID 1:', post1); // { id: 1, title: 'First Post', published: false }

// Update a document by ID
_.updateById(db.posts, newPost.id, { published: true });
console.log('Updated post:', _.getById(db.posts, newPost.id)); // { id: 3, title: 'Third Post', published: true }

// Upsert a document (replaces if ID exists, inserts if not)
_.upsert(db.posts, { id: 1, title: 'First Post Updated', category: 'News' });
console.log('Upserted post 1:', _.getById(db.posts, 1)); // { id: 1, title: 'First Post Updated', category: 'News' }

// Remove a document by ID
const removedPost = _.removeById(db.posts, 2);
console.log('Removed post by ID 2:', removedPost); // { id: 2, title: 'Second Post', published: true }
console.log('Remaining posts:', db.posts); // [{ id: 1, title: 'First Post Updated', category: 'News' }, { id: 3, title: 'Third Post', published: true }]

view raw JSON →