pick
Pick only the desired properties from an object
266 bytes
Usage
Given an object and a list of keys in the object, returns a new object with only the given keys.
import * as _ from 'radashi'
const fish = { name: 'Bass', weight: 8, source: 'lake', brackish: false,}
_.pick(fish, ['name', 'source']) // => { name, source }
Predicate function
The pick
function can also accept a predicate function as the filter argument. This allows for more complex filtering logic beyond simple key inclusion or exclusion.
import * as _ from 'radashi'
const source = { a: 1, b: 2, c: 3, d: 4 }
_.pick(source, (value, key) => { return value % 2 === 0 // Include only even values})// => { b: 2, d: 4 }
Unsafe predicate function
// Example demonstrating potential inaccuracy in `key` and `value` types within `_.pick` callbackimport * as _ from 'radashi'
interface User { name: string age: number}
function getUserDetails(user: User) { return _.pick(user, (value, key) => { // TypeScript believes `key` is 'name' | 'age', but at runtime // it could be 'email' if (key === 'name' || key === 'age') { console.log(key, '=', value) } else { // TypeScript believes this will never run, but it does. console.log('Unexpected key:', key) } })}
// At runtime, the function may receive an object with more propertiesconst runtimeUser = { name: 'John', age: 30, // This property is not listed in the User type: email: 'john@example.com',}
getUserDetails(runtimeUser)// Logs the following:// name = John// age = 30// Unexpected key: email