ArticleZip > Filter Object Properties By Key In Es6

Filter Object Properties By Key In Es6

In ES6, also known as ECMAScript 2015, we have a powerful feature called object destructuring that allows us to easily extract specific properties from objects. However, there might be times when you need to filter object properties by key in ES6 for various reasons. In this article, we will discuss how you can achieve this using a simple and efficient method.

To filter object properties by key in ES6, we can make use of the Object.keys() method combined with the Array.reduce() method. Let's break down the process step by step for better understanding.

First, let's consider an example object that we want to filter:

Javascript

const sampleObject = {
  name: 'John',
  age: 30,
  city: 'New York',
  profession: 'Engineer'
};

Now, let's say we want to filter out only the properties with keys 'name' and 'age'. Here's how you can achieve this using ES6 features:

Javascript

const filteredObject = Object.keys(sampleObject)
  .filter(key => ['name', 'age'].includes(key))
  .reduce((obj, key) => {
    obj[key] = sampleObject[key];
    return obj;
  }, {});

console.log(filteredObject);

In the above code snippet, we first use Object.keys(sampleObject) to get an array of all the keys in the sampleObject. We then apply the filter method to this array, which will only keep the keys 'name' and 'age'. The includes() method is used to check if the current key is present in the array of keys we want to filter by.

Next, we use the reduce method to create a new object that only contains the filtered properties. Inside the reducer function, we assign each property from the original object to the new object if its key matches the filtered keys.

After running this code, you will get a new object stored in the filteredObject variable that contains only the 'name' and 'age' properties from the sampleObject. You can customize the keys to filter by simply modifying the array passed to the includes() method.

Filtering object properties by key in ES6 can be especially handy when you want to manipulate or display specific data from an object without needing all its properties. It provides a clean and concise way to work with objects in JavaScript, leveraging the power of modern ES6 syntax.

So, next time you find yourself needing to filter object properties by key in ES6, remember this handy technique using Object.keys(), filter(), and reduce() methods. Happy coding!

×