Introduction
In JavaScript, objects are a fundamental data structure that allows developers to store key-value pairs. At times, there may be a need to filter an object’s properties based on specific keys—creating a new object containing only the desired subsets of the original. This tutorial explores various methods in ES6 and beyond for achieving this filtering using modern JavaScript features.
Using Object.keys(), Array.filter(), and Array.reduce()
One common method involves using Object.keys()
to retrieve an array of property names, Array.prototype.filter()
to select specific keys, and Array.prototype.reduce()
to construct a new object. Here’s how you can implement it:
const raw = {
item1: { key: 'sdfd', value:'sdfd' },
item2: { key: 'sdfd', value:'sdfd' },
item3: { key: 'sdfd', value:'sdfd' }
};
const allowedKeys = ['item1', 'item3'];
const filteredObject = Object.keys(raw)
.filter(key => allowedKeys.includes(key))
.reduce((obj, key) => {
obj[key] = raw[key];
return obj;
}, {});
console.log(filteredObject);
Explanation
- Object.keys(raw): Converts the object’s keys into an array.
- Array.prototype.filter(): Filters this array to include only allowed keys.
- Array.prototype.reduce(): Iteratively builds a new object with these filtered properties.
This method provides a clean, functional approach to filtering objects.
Utilizing Object Destructuring
ES6 introduced destructuring, which can simplify the task of excluding certain keys:
const raw = {
item1: { key: 'sdfd', value:'sdfd' },
item2: { key: 'sdfd', value:'sdfd' },
item3: { key: 'sdfd', value:'sdfd' }
};
// Exclude `item2` and gather the rest
const { item2, ...filteredObject } = raw;
console.log(filteredObject);
Explanation
- Destructuring: The syntax
{ item2, ...rest }
excludesitem2
from the new object while gathering all other properties intofilteredObject
. - This method is particularly useful when you want to exclude only one or a few specific keys without listing all others.
Using Object.fromEntries() and Array.entries()
For a more concise approach, ES2021 introduced Object.fromEntries()
, which converts key-value pairs back into an object. Combined with Array.prototype.filter()
and Array.prototype.entries()
, it can efficiently filter properties:
const raw = { item1: { prop:'1' }, item2: { prop:'2' }, item3: { prop:'3' } };
const allowedKeys = ['item1', 'item3'];
const filteredObject = Object.fromEntries(
Object.entries(raw).filter(([key, _]) => allowedKeys.includes(key))
);
console.log(filteredObject);
Explanation
- Object.entries(): Converts the object into an array of
[key, value]
pairs. - Array.prototype.filter(): Filters this array based on allowed keys.
- Object.fromEntries(): Reconstructs an object from the filtered key-value pairs.
This method is powerful and succinct, leveraging new JavaScript features for clear and readable code.
Using Lodash’s pick Function
For those using utility libraries like Lodash, _.pick()
provides a straightforward way to filter objects:
const _ = require('lodash');
const raw = {
item1: { key: 'sdfd', value:'sdfd' },
item2: { key: 'sdfd', value:'sdfd' },
item3: { key: 'sdfd', value:'sdfd' }
};
const allowedKeys = ['item1', 'item3'];
const filteredObject = _.pick(raw, allowedKeys);
console.log(filteredObject);
Explanation
- Lodash’s pick(): Filters the object to include only specified keys.
- This method is ideal when using libraries for cleaner code and utility functions.
Conclusion
Filtering an object’s properties by key can be approached in multiple ways depending on your needs and preferred coding style. Whether through native JavaScript methods, destructuring, or utilities like Lodash, ES6 and beyond provide powerful tools to manipulate objects elegantly and efficiently. Choose the method that best fits your project requirements and coding preferences.