JavaScript Filter Object by Key
Filtering an object means extracting elements from an object based on certain conditions.
An object can have many properties but for certain tasks, like cleaning data, for analysis, you may need to filter out properties of the object and bring only necessary properties on the table.
For this, you will need to filter out JavaScript objects. Although a JavaScript object does not have a filter() method but you can turn an object into an array for this.
In this article, you will see how to filter JavaScript objects.
Filtering Objects in JavaScript
To filter an object by its keys, you need to follow these steps:
- Get the object's key using the Object.keys() method.
- Use the filter() method to filter the keys based on the condition.
- Use the reduce() method to create a new object from the filtered keys.
Let's see an example to filter an object by its keys.
Example 1: Filter Object by Key
In the following example, we will filter out the properties that start with 'person_' and create a new object from the filtered keys.
Example
const person = {
person_name: 'Alice',
person_age: 25,
person_email: '[email protected]',
person_address: '123 Street',
job_title: 'Developer',
};
// filter out keys that starts with 'person_'
const filteredKeys = Object.keys(person)
.filter(key => key.startsWith('person_'));
// create new object from filtered keys
const filteredObject = {};
filteredKeys.forEach(key => {
filteredObject[key] = person[key];
});
console.log(filteredObject);
Example 2:
In the following example, we will filter out the properties that are of type 'string' and create a new object from the filtered keys.
Example
const items = {
item1: 'item1',
item2: 2,
item3: 'item3',
item4: 4,
item5: 'item5'
};
// filter out keys that are of type 'string'
const filteredKeys = Object.keys(items)
.filter(key => typeof items[key] === 'string');
// create new object from filtered keys
const filteredObject = {};
filteredKeys.forEach(key => {
filteredObject[key] = items[key];
});
console.log(filteredObject);
Example 3:
There can also be a case when you already have a list of keys that you want to filter out from the object. Let's see how to do that.
Example
const userProfile = {
name: 'Jane Doe',
age: 28,
email: '[email protected]',
address: '123 Main St',
phone: '555-123-4567',
};
// keys to filter out
const keysToFilter = ['email', 'address', 'phone'];
// filter out keys
const filteredKeys = Object.keys(userProfile)
.filter(key => !keysToFilter.includes(key));
// create new object from filtered keys
const filteredObject = {};
filteredKeys.forEach(key => {
filteredObject[key] = userProfile[key];
});
console.log(filteredObject);
Conclusion
You have learned how to filter an object by its keys in JavaScript. We have seen 3 different examples that cover most of the use cases.
Although there are many other ways to filter an object by its keys, the above examples are the most efficient and easy to understand.
Hope you found this guide useful.