Explain Codes LogoExplain Codes Logo

Filter object properties by key in ES6

javascript
prompt-engineering
functions
spread-syntax
Nikita BarsukovbyNikita Barsukov·Jan 11, 2025
TLDR

Use the Object.fromEntries() and Object.entries() functions combined with .filter() to create a new object that retains only the specified properties:

const obj = { a: 1, b: 2, c: 3 }; // Original object const keysToKeep = ['a', 'c']; // We only like 'a' and 'c' const filteredObj = Object.fromEntries( Object.entries(obj).filter(([key]) => keysToKeep.includes(key)) ); console.log(filteredObj); // { a: 1, c: 3 }, 'b' is feeling left out

This example produces an object free of any unwanted properties. The object solely contains the keys a and c.

Level up your code with modern JavaScript

Incorporate reduce() with arrow functions and the spread syntax to code like a pro. Behold the upgraded implementation:

const filterObjectKeys = (obj, keys) => keys.reduce((acc, key) => (key in obj ? { ...acc, [key]: obj[key] } : acc), {}); // else acc is thinking: why always me, when there's no key?

Now, you possess a general function to filter the properties of any object, using any set of keys.

Avoid mutation: A safer pathway

When working with objects, it's safer to create a shallow copy, maintaining the original object untouched. Mutation can cause unwanted side-effects (it's like not washing your coffee mug, it all adds up). With ES6's spread operator, you can easily steer clear from this:

const filteredCopy = { ...filteredObj }; // Don't worry, original object, you're safe

This method ensures no reference to the original object's properties is maintained and adds an extra layer of safety to your code.

Diving into dynamic filtering

Your key list can become more dynamic with functions. You can filter your object's properties by making your criteria function alter the values too! It's like being at a party and saying you only want guests who bring fun and food:

const dynamicFilter = (obj, predicate) => Object.fromEntries(Object.entries(obj).filter(([key, value]) => predicate(key, value))); const criteria = (key, value) => key.startsWith('a') && value > 0; const allowed = dynamicFilter(obj, criteria); // Party is on!

The example above allows you to filter an object's properties based on values in addition to keys.

Dodging potential pitfalls and mastering edge cases

Be sure to remember that Object.fromEntries() may not be available everywhere like free Wi-Fi. In situations where your trusty ES6 spread operator isn’t supported, you might need back-up polyfills or alternatives. Also, while creating shallow copies works marvelously in most cases, for deeply nested objects, properties may still hold onto their original values (kind of like how deep feelings remain even after an outward change).

Making it simple with utility libraries

If you prefer a more readable and declarative approach, consider using utility libraries like Lodash. Its _.pick method can make filtering properties a non-chore:

const _ = require('lodash'); const picked = _.pick(obj, keysToKeep); // Lodash says: leave the heavy lifting to me

Meeting diverse requirements with tailored solutions

Depending on the application's requirements, the approach to filter object properties must fit like a glove. Remember, your code should be as readable, maintainable, and performant as a Tesla. But tread wisely with library dependencies, as they might come with their own caveats (like more nodes in your dependency tree).