Skip to content

Instantly share code, notes, and snippets.

@hansamlin
Last active December 19, 2022 08:29
Show Gist options
  • Save hansamlin/794f0133fd238be8920d632ab1c7d6b0 to your computer and use it in GitHub Desktop.
Save hansamlin/794f0133fd238be8920d632ab1c7d6b0 to your computer and use it in GitHub Desktop.
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