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:
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!