UNPKG

@nex-ui/utils

Version:

Utility functions for React components.

31 lines (28 loc) 954 B
import { isPlainObject } from './is.mjs'; const isNotNullish = (element)=>element != null; function walkObject(target, fn, options = {}) { const { predicate, getKey } = options; function inner(value, path = []) { if (isPlainObject(value) || Array.isArray(value)) { const result = {}; for (const [prop, child] of Object.entries(value)){ const key = getKey?.(prop, child) ?? prop; const childPath = [ ...path, key ]; if (predicate?.(value, childPath)) { return fn(value, path); } const next = inner(child, childPath); if (isNotNullish(next)) { result[key] = next; } } return result; } return fn(value, path); } return inner(target); } export { walkObject };