How to filter object by keys or values in JavaScript

Sep 20, 2023#javascript

Filtering keys allows you to transform and shape your data to match your applicationā€™s requirements. By selecting only the keys you need, you can create a new object that contains a more concise and relevant subset of data.

When dealing with sensitive data, such as user profiles or credentials, filtering keys allows you to create sanitized versions of objects. This can help protect sensitive information from being accidentally exposed or leaked.

You can create a new object in JavaScript by filtering out specific keys from an existing object using various methods. Here are a few common approaches to achieve this:

  1. Using object destructuring to extract values from an object property and assign them to a variable, then using rest operator (...) to collect the remaining properties of an object into a new object.
const person = {
  name: 'Alice',
  age: 25,
  occupation: 'developer',
  hobbies: ['reading', 'gaming', 'coding']
};

const { name, age, ...rest } = person;
console.log(rest); 
// { occupation: 'developer', hobbies: ['reading', 'gaming', 'coding'] }
  1. Using the Object.keys() method to create a new object by iterating through the keys of the original object and filtering out the desired keys:
const originalObject = {
  name: 'Alice',
  age: 25,
  occupation: 'developer',
  hobbies: ['reading', 'gaming', 'coding']
};

const keysToExclude = ["name", "age"];

const filteredObject = Object.keys(originalObject).reduce((result, key) => {
  if (!keysToExclude.includes(key)) {
    result[key] = originalObject[key];
  }
  return result;
}, {});

console.log(filteredObject);
// { occupation: 'developer', hobbies: ['reading', 'gaming', 'coding'] }
  1. Using a for...in loop to iterate through the keys of the original object and build a new object while excluding specific keys:
const originalObject = {
  name: 'Alice',
  age: 25,
  occupation: 'developer',
  hobbies: ['reading', 'gaming', 'coding']
};

const keysToExclude = ["name", "age"];
const filteredObject = {};

for (const key in originalObject) {
  if (!keysToExclude.includes(key)) {
    filteredObject[key] = originalObject[key];
  }
}

console.log(filteredObject);
// { occupation: 'developer', hobbies: ['reading', 'gaming', 'coding'] }

This approach allows you to create a new object while omitting keys listed in the keysToExclude array.

  1. Using Object.entries() function, which returns an array of key-value pairs for the given object. Then, you can use the Array.filter() function to filter out the pairs that do not match the desired value. Finally, you can use the Object.fromEntries() function to convert the filtered array back to an object. For example, suppose you have an object like this:
const originalObject = {
  name: 'Alice',
  age: 25,
  occupation: 'developer',
  hobbies: ['reading', 'gaming', 'coding']
};

const entries = Object.entries(originalObject);

// Filter out the pairs that do not have the value "Alice"
const filteredEntries = entries.filter(([key, value]) => value === "Alice");

// Convert the filtered array back to an object
const filteredObject = Object.fromEntries(filteredEntries);

console.log(filteredObject); // { name: 'Alice' }
  1. Using libraries like Lodash, which provides utility functions to perform various operations on objects, including filtering by keys or values.

In Lodash, both _.pick() and _.pickBy() are utility functions used to create a new object by selecting specific properties (keys) from an input object. However, they serve slightly different purposes:

Method _.pick() is primarily used for selecting specific properties (keys) from an object based on a list of property names you provide. It returns a new object that includes only the properties specified in the list of keys.

const _ = require('lodash');

const originalObject = {
  name: 'Alice',
  age: 25,
  occupation: 'developer',
  hobbies: ['reading', 'gaming', 'coding']
};

const filteredObject = _.pick(originalObject, ['name', 'age']);

console.log(filteredObject); // { name: 'Alice', age: 25 }

Method _.pickBy() is used to create a new object by selecting properties (keys) from an input object based on a predicate function. This function allows you to filter properties based on their values. It returns a new object containing only the properties for which the predicate function returns true.

const _ = require('lodash');

const originalObj = { a: 1, b: 2, c: 3, d: 4 };
const pickedByObj = _.pickBy(originalObj, (value, key) => value % 2 === 1); // Selects odd-valued properties
console.log(pickedByObj); // { a: 1, c: 3 }