Last active
September 19, 2021 22:31
-
-
Save signalwerk/eadabea1fc42795ed8af2882693d20e1 to your computer and use it in GitHub Desktop.
reduced lodash get() function in vanilla javascript
This file contains hidden or 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
| /** | |
| * https://gist.github.com/signalwerk/eadabea1fc42795ed8af2882693d20e1 | |
| * | |
| * Return the value at `path` in `object` | |
| * @param {Object} object | |
| * @param {string|array} path | |
| * @returns {*} value if found otherwise undefined | |
| */ | |
| export const get = (object, path) => { | |
| let parts = path; | |
| if (typeof path === "string" || typeof path === "number") { | |
| parts = `${path}`.split(/[\.\[\]\"\']{1,2}/).filter((part) => !!part); | |
| } | |
| return parts.reduce((acc, part) => (acc ? acc[part] : undefined), object); | |
| }; | |
| // thanks to https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-and-arrays-by-string-path | |
| /* | |
| const test = { | |
| a: { aa: "get a.aa" }, | |
| b: { bb: [0, "get a.bb[1]"] }, | |
| c: { cc: false }, | |
| }; | |
| console.log("test A", get(test, "a.aa")); | |
| console.log("test B", get(test, "b.bb[1]")); | |
| console.log("test C", get(test, "b.['bb'][1]")); | |
| console.log("test D", get(test, 'b.["bb"][1]')); | |
| console.log("test E", get(test, ["b", "bb", 1])); | |
| console.log("test F", get(test, ["b", "bb", 2])); | |
| console.log("test G", get(test, "c.cc")); | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment