Skip to content

filterKey

Check if an object key passes a filter

146 bytes

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
filter
:
import _
_
.
type KeyFilter<T extends object = object, Key extends keyof any = string | number | symbol> = _.KeyFilterFunction<T> | readonly Key[]
export KeyFilter

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)
export filterKey

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
filter
)) {
// ...
}
}
}