Skip to content

How to filter an object by key in JavaScript?

We can use these code snippets to filter a JavaScript object their keys.

Filter and reduce with Object.keys()

const obj = { employeeId: 'TRE54673DF', accountId: 'ExS76422', name: 'Nanand' };

Object.keys(obj).filter((key) => key.includes('Id')).
  reduce((cur, key) => { return Object.assign(cur, { [key]: obj[key] })}, {});

//{ accountId:ExS76422,employeeId:TRE54673DF }
Advertisements

Filter with Object.entries()

const obj = { employeeId: 'TRE54673DF', accountId: 'ExS76422', name: 'Nanand' };
Object.fromEntries(Object.entries(obj).filter(([key]) => key.includes('Id')));
//{ accountId:ExS76422,employeeId:TRE54673DF }
See also  Converting an Array of Objects to an Object

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.