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')));
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!