Home  >  Article  >  Web Front-end  >  How to Filter Object Properties by Key in ES6?

How to Filter Object Properties by Key in ES6?

Linda Hamilton
Linda HamiltonOriginal
2024-11-09 17:02:02288browse

How to Filter Object Properties by Key in ES6?

Filtering Object Properties by Key in ES6

In JavaScript, it's often necessary to filter object properties based on specific criteria. ES6 provides a clean and efficient way to achieve this through spread operators.

Problem:

Given an object like:

{
  item1: { key: 'sdfd', value: 'sdfd' },
  item2: { key: 'sdfd', value: 'sdfd' },
  item3: { key: 'sdfd', value: 'sdfd' }
}

The goal is to create a new object that only includes properties with specific keys, such as:

{
  item1: { key: 'sdfd', value: 'sdfd' },
  item3: { key: 'sdfd', value: 'sdfd' }
}

Solution:

ES6 allows us to filter object properties using a combination of the Object.keys() and Array.filter() methods, followed by the Array.reduce() method to create the new object.

The provided code demonstrates this approach:

const raw = {
  item1: { key: 'sdfd', value: 'sdfd' },
  item2: { key: 'sdfd', value: 'sdfd' },
  item3: { key: 'sdfd', value: 'sdfd' }
};

const allowed = ['item1', 'item3'];

const filtered = Object.keys(raw)
  .filter(key => allowed.includes(key))
  .reduce((obj, key) => {
    obj[key] = raw[key];
    return obj;
  }, {});

console.log(filtered);

In this code:

  1. Object.keys(raw) extracts the object keys into an array.
  2. Array.filter(key => allowed.includes(key)) filters the keys based on the allowed values.
  3. Array.reduce((obj, key) => { /* ... */ }, {}) reduces the filtered keys into a new object, copying the corresponding property values from the original object.

The above is the detailed content of How to Filter Object Properties by Key in ES6?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn