AshKeys

Confessions and Confusions of Ashok M A. Personal and Professional Blog.

Ashok Mannolu Arunachalam, How toArraysES6JS
Back

How to filter Object properties like arrays in JS

Recently I had to find a compact solution to filter out a set of properties from an array of objects.

In short, the users select which properties they want to see in order to customize the propiew.

In arrays, it is pretty simple by using the Array.filter but for objects we need a receipe such as the below one.

js
const persons = [
{
name: 'AshKeys',
occupation: 'Full Stack Developer',
blog: 'Fullstacker.nl'
},
{
name: 'Sojiro',
occupation: 'Web Developer',
blog: 'Fullstacker.nl'
}
]
const filters = ['name', 'occupation']
console.table(persons)
/**
┌─────────┬───────────┬────────────────────────┬──────────────────┐
│ (index) │ name │ occupation │ blog │
├─────────┼───────────┼────────────────────────┼──────────────────┤
│ 0 │ 'AshKeys' │ 'Full Stack Developer' │ 'Fullstacker.nl' │
│ 1 │ 'Sojiro' │ 'Web Developer' │ 'Fullstacker.nl' │
└─────────┴───────────┴────────────────────────┴──────────────────┘
**/
const filteredPersons = persons.map((p) =>
Object.keys(p)
.filter((prop) => filters.includes(prop))
.reduce((acc, prop) => ({ ...acc, [prop]: p[prop] }), {})
)
console.table(filteredPersons)
/**
┌─────────┬───────────┬────────────────────────┐
│ (index) │ name │ occupation │
├─────────┼───────────┼────────────────────────┤
│ 0 │ 'AshKeys' │ 'Full Stack Developer' │
│ 1 │ 'Sojiro' │ 'Web Developer' │
└─────────┴───────────┴────────────────────────┘
**/

Try to achieve the same by iterating the filters array.