How to Filter an Object by Key in JavaScript
Aug 19, 2021
JavaScript objects don't have a filter()
method, you must first turn the object into an array to use array's filter()
method.
You can use the Object.keys()
function to convert the object's keys into an array, and accumulate the filtered keys into a new object using the reduce()
function as shown below.
const obj = { firstName: 'Jean-Luc', lastName: 'Picard', age: 59 };
// { firstName: 'Jean-Luc', lastName: 'Picard' }
Object.keys(obj).
filter((key) => key.includes('Name')).
reduce((cur, key) => { return Object.assign(cur, { [key]: obj[key] })}, {});
Another option is to convert the object into an array of entries using Object.entries()
, filter the entries, and then convert the array of entries back into an object using Object.fromEntries()
.
const obj = { firstName: 'Jean-Luc', lastName: 'Picard', age: 59 };
// { firstName: 'Jean-Luc', lastName: 'Picard' }
Object.fromEntries(Object.entries(obj).filter(([key]) => key.includes('Name')));
More Fundamentals Tutorials
- How to Add 2 Arrays Together in JavaScript
- The String `match()` Function in JavaScript
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript