JavaScript Snippet

Pick a Subset of Object Keys

Difficulty: Easy

Picking a whitelist of fields from an object is a daily chore for API responses, form submissions, and analytics events. This snippet covers the canonical Object.fromEntries filter, a typed-friendly variant that drops missing keys, and a generic helper that picks by predicate. Stop hand-rolling it for every endpoint and reach for the version that fits your data.

Code Snippets
/

Pick a Subset of Object Keys

Pick a Subset of Object Keys

Picking a whitelist of fields from an object is a daily chore for API responses, form submissions, and analytics events. This snippet covers the canonical Object.fromEntries filter, a typed-friendly variant that drops missing keys, and a generic helper that picks by predicate. Stop hand-rolling it for every endpoint and reach for the version that fits your data.

JavaScript
Easy
3 snippets
utility
code-template
js-spread-rest

245 views

2

The cleanest one-liner walks the object's own enumerable entries and keeps only the pairs whose key is in the whitelist. Object.fromEntries then rebuilds an object from the surviving [key, value] tuples. This runs in O(n + m) where n is the entry count and m is the keys list, and it never touches inherited properties because Object.entries only sees own enumerable keys. Use this when you trust the whitelist source and don't care that absent keys silently disappear from the result.