-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #202 from Amsterdam/WON-72-maak-telefoon-veld-nume…
…riek-in-zaak-aanmaak-formulier WON-72 phone numeric
- Loading branch information
Showing
4 changed files
with
77 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/** | ||
* Returns a value from an object by following a given path, which can be a string or array. | ||
* | ||
* Example: | ||
* | ||
* const obj = { user: { name: "Alice", age: 25, addresses: [{ city: "Wonderland" } } }; | ||
* const result = getValueByPath(obj, "user.address.city"); // Returns "Wonderland" | ||
* | ||
* const obj = { users: [{ name: "Alice" }, { name: "Bob" }] }; | ||
* const result = getValueByPath(obj, "users[1].name"); // Returns "Bob" | ||
* | ||
* COPY of Lodash GET function | ||
*/ | ||
|
||
type Path = string | Array<string | number> | ||
type Value = boolean | string | object | ||
|
||
export function getValueByPath<T, R = undefined>( | ||
obj: T, | ||
path: Path, | ||
defaultValue?: R | ||
): R | Value { | ||
if (!obj || !path) return defaultValue as R | ||
|
||
const pathArray = Array.isArray(path) | ||
? path | ||
: path.replace(/\[(\d+)]/g, ".$1").split(".") | ||
|
||
let current: Value = obj | ||
|
||
for (const key of pathArray) { | ||
if (current && typeof current === "object" && key in current) { | ||
current = (current as Record<string | number, Value>)[key] | ||
} else { | ||
return defaultValue as R | ||
} | ||
} | ||
|
||
return current | ||
} |