(params: FlattenParams = {}, propertyPath?: string, options?: GetOptions)
| 18 | * them |
| 19 | */ |
| 20 | const get = (params: FlattenParams = {}, propertyPath?: string, options?: GetOptions): any => { |
| 21 | if (!propertyPath) { |
| 22 | return flat.unflatten(params) |
| 23 | } |
| 24 | |
| 25 | // when object has this key - simply return it |
| 26 | // we cannot rely on typeof params[propertyPath !== 'undefined' because params can actually be |
| 27 | // undefined and in such case if would pass and function would return [undefined] |
| 28 | if (Object.keys(params).find((key) => (key === propertyPath))) { |
| 29 | return params[propertyPath] |
| 30 | } |
| 31 | |
| 32 | const regex = propertyKeyRegex(propertyPath, options) |
| 33 | const selectedParams = selectParams(params, propertyPath, options) |
| 34 | |
| 35 | const nestedProperties = Object.keys(selectedParams).reduce((memo, key, index) => { |
| 36 | let newKey = key.replace(regex, `${TEMP_HOLDING_KEY}${DELIMITER}`) |
| 37 | |
| 38 | // when user wants to take allSiblings we have to fix the indexes so nested items from |
| 39 | // different siblings don't overlap |
| 40 | // |
| 41 | // Example for key `nested.1.el`: |
| 42 | // 'nested.0.el.0.value': 'val0.0', |
| 43 | // 'nested.0.el.1.value': 'val0.1', |
| 44 | // 'nested.1.el.0.value': 'val1', |
| 45 | // 'nested.1.el.1.value': 'val2', |
| 46 | // |
| 47 | // has to be changed to: |
| 48 | // 'TEMP_HOLDING_KEY.0.value': 'val0.0', |
| 49 | // 'TEMP_HOLDING_KEY.1.value': 'val0.1', |
| 50 | // 'TEMP_HOLDING_KEY.2.value': 'val1', |
| 51 | // 'TEMP_HOLDING_KEY.3.value': 'val2', |
| 52 | if (options?.includeAllSiblings) { |
| 53 | newKey = newKey.replace( |
| 54 | new RegExp(`${TEMP_HOLDING_KEY}\\${DELIMITER}(\\d*)`), |
| 55 | `${TEMP_HOLDING_KEY}${DELIMITER}${index}`, |
| 56 | ) |
| 57 | } |
| 58 | |
| 59 | memo[newKey] = selectedParams[key] |
| 60 | |
| 61 | return memo |
| 62 | }, {} as FlattenParams) |
| 63 | |
| 64 | if (Object.keys(nestedProperties).length) { |
| 65 | return (flat.unflatten(nestedProperties) as Record<string, unknown>)[TEMP_HOLDING_KEY] |
| 66 | } |
| 67 | return undefined |
| 68 | } |
| 69 | |
| 70 | export { get } |
no test coverage detected