6

How to Filter an Object by Key in JavaScript

 2 years ago
source link: https://masteringjs.io/tutorials/fundamentals/filter-key
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK