mirror of
https://github.com/dzeiocom/libs.git
synced 2025-06-07 00:29:56 +00:00
feat(object-util): Add two functions objectFilter
& objectPick
Signed-off-by: Avior <git@avior.me>
This commit is contained in:
parent
91a6409e90
commit
24d598f415
@ -385,6 +385,39 @@ export function objectGet<T = any>(obj: any, path: Array<string | number | symbo
|
||||
throw new Error(`it should never get there ! (${JSON.stringify(obj)}, ${path}, ${JSON.stringify(pointer)})`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Only return the specified keys from the object
|
||||
*
|
||||
* @param obj the object to pick from
|
||||
* @param keys the keys to keep
|
||||
* @returns a new copy of `obj` with only `keys` in it
|
||||
*/
|
||||
function objectPick<V, K extends string | number | symbol>(obj: Record<K, V>, ...keys: Array<K>): Pick<Record<K, V>, K> {
|
||||
mustBeObject(obj)
|
||||
return objectFilter(obj, (_, k) => keys.includes(k)) as Pick<Record<K, V>, K>
|
||||
}
|
||||
|
||||
/**
|
||||
* filter elements from the object and return a new copy
|
||||
*
|
||||
* @param obj the object to filter
|
||||
* @param fn the function to pass it through
|
||||
* @returns the filtered object
|
||||
*/
|
||||
function objectFilter<V, K extends string | number | symbol>(obj: Record<K, V>, fn: (v: V, k: K, idx: number) => boolean): Partial<Record<K, V>> {
|
||||
mustBeObject(obj)
|
||||
const clone: Partial<Record<K, V>> = {}
|
||||
objectLoop(obj, (v, k, idx) => {
|
||||
const res = fn(v, k, idx)
|
||||
if (res) {
|
||||
clone[k] = v
|
||||
}
|
||||
})
|
||||
|
||||
return clone
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* return if an item is an object
|
||||
*
|
||||
@ -414,12 +447,14 @@ export default {
|
||||
objectClean,
|
||||
objectClone,
|
||||
objectEqual,
|
||||
objectFilter,
|
||||
objectFind,
|
||||
objectGet,
|
||||
objectKeys,
|
||||
objectLoop,
|
||||
objectMap,
|
||||
objectOmit,
|
||||
objectPick,
|
||||
objectRemap,
|
||||
objectSet,
|
||||
objectSize,
|
||||
|
Loading…
x
Reference in New Issue
Block a user