Last active
December 19, 2022 08:29
-
-
Save hansamlin/794f0133fd238be8920d632ab1c7d6b0 to your computer and use it in GitHub Desktop.
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
function _get(obj, path, _default) { | |
if (typeof obj !== "object") { | |
throw new Error("param 1 must be an object") | |
} | |
if (typeof path !== "string" && !Array.isArray(path)) { | |
throw new Error("param 2 must be an object or a string") | |
} | |
let _path = path | |
if (typeof _path === "string") { | |
const pathArr = _path.split(".").map(str => { | |
return str.split(/([a-zA-Z]*)\[(\d+)\]/g).filter(e => e) | |
}).flat(); | |
} | |
try { | |
let tmp = obj; | |
for (let i = 0; i < _path.length; i += 1) { | |
tmp = tmp[_path[i]] | |
if (!tmp) { | |
return _default | |
} | |
} | |
return tmp; | |
} catch (error) { | |
return _default; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment