What is filter-obj?
The filter-obj npm package allows users to filter the properties of an object based on specific criteria. This can be useful for creating subsets of an object, removing unwanted properties, or selectively copying properties based on dynamic conditions.
What are filter-obj's main functionalities?
Filtering based on property names
This feature allows you to filter an object by specifying which property names to keep. It is useful for extracting specific properties from an object.
const filterObj = require('filter-obj');
const obj = { a: 1, b: '2', c: 3 };
const filtered = filterObj(obj, ['a', 'c']);
console.log(filtered); // Output: { a: 1, c: 3 }
Filtering using a function
This feature enables filtering based on a function that takes key and value as arguments. It allows for more dynamic and condition-based filtering, such as filtering out properties based on their types or values.
const filterObj = require('filter-obj');
const obj = { a: 1, b: '2', c: 3 };
const filtered = filterObj(obj, (key, value) => typeof value === 'number');
console.log(filtered); // Output: { a: 1, c: 3 }
Other packages similar to filter-obj
lodash.pick
lodash.pick is a method from the Lodash library that creates an object composed of the picked object properties. It is similar to filter-obj but is part of a larger utility library, which might be preferable for users who need other utility functions.
object-filter
object-filter is another npm package that provides similar functionality to filter-obj, allowing filtering of object properties based on a predicate function. It compares to filter-obj in terms of functionality but might have different implementation details or additional options.
filter-obj
Filter object keys and values into a new object
Install
npm install filter-obj
Usage
import {includeKeys, excludeKeys} from 'filter-obj';
const object = {
foo: true,
bar: false
};
const newObject = includeKeys(object, (key, value) => value === true);
const newObject2 = includeKeys(object, ['bar']);
const newObject = excludeKeys(object, (key, value) => value === true);
const newObject3 = excludeKeys(object, ['bar']);
API
includeKeys(source, filter)
includeKeys(source, keys)
excludeKeys(source, filter)
excludeKeys(source, keys)
source
Type: object
The source object to filter properties from.
filter
Type: (sourceKey: string | symbol, sourceValue: unknown, source: object) => boolean
A predicate function that determines whether a property should be filtered.
keys
Type: Array<string | symbol> | Set<string | symbol>
An array or Set
of property keys to be filtered.
Related
- map-obj - Map object keys and values into a new object