188k views
4 votes
How to Filter an Object by Key in JavaScript?

User CHANist
by
6.9k points

1 Answer

5 votes

Final answer:

In JavaScript, to filter an object by key, you use Object.keys in conjunction with filter and reduce to create a new object with only the desired keys.

Step-by-step explanation:

To filter an object by key in JavaScript, you can use the Object.keys method in combination with the filter method and reduce method to create a new object that only contains the keys that satisfy a particular condition. Here is an example:

const originalObject = { a: 1, b: 2, c: 3, d: 4 };
const filterKeys = ['a', 'd'];
const filteredObject = Object.keys(originalObject)
.filter(key => filterKeys.includes(key))
.reduce((obj, key) => {
obj[key] = originalObject[key];
return obj;
}, {});

In this example, filterKeys contains the keys you want to retain. The filter method is used to keep only those keys, and the reduce method is used to construct a new object with just those keys.

User Kreisquadratur
by
7.7k points