Skip to content

filterKey

Check if an object key passes a filter

156 bytes
since v12.2.0

Usage

You have a utility function that is filtering an object’s properties somehow. Using filterKey will allow your function to filter those properties based on either an array of keys (an allowlist) or a function that returns a boolean for each property.

The KeyFilter type provided by Radashi is fundamental in taking advantage of the filterKey function. Be sure to use it to ensure type safety and maintainable code.

import * as
import _
_
from 'radashi'
function
function filterObject(obj: object, filter: _.KeyFilter): void
filterObject
(
obj: object
obj
: object,
filter: _.KeyFilter<object, string | number | symbol>
filter
:
import _
_
.
type KeyFilter<T extends object = object, Key extends keyof any = string | number | symbol> = _.KeyFilterFunction<T> | readonly Key[]

Functions can use this type to accept either an array of keys or a filter function.

@version12.2.0

KeyFilter
) {
for (const
const key: string
key
in
obj: object
obj
) {
if (
import _
_
.
function filterKey(obj: object, key: keyof any, filter: _.KeyFilter | null | undefined): boolean (+1 overload)

Returns true if the key is in the “keys array” or if the “filter function” returns true. This function is useful when creating other functions that need to enumerate an object or array and filter keys in a flexible manner. Using it directly in everyday code is not recommended.

@seehttps://radashi.js.org/reference/object/filterKey

@example

const a = { a: 1, b: 2, c: 3 }
filterKey(a, 'a', ['a', 'b'])
// => true
filterKey(a, 'a', ['a', 'b'])
// => true

filterKey
(
obj: object
obj
,
const key: string
key
,
filter: _.KeyFilter<object, string | number | symbol>
filter
)) {
// ...
}
}
}