This afternoon I used lodash.get
together with react-hook-form
to display error message in a form and I got the idea I could try to implement get
myself as some type of brain training.
This implementation covers only use case when the path is string. Also I didnt cover get's defaultValue
param.
I used the same test
object as one used in lodash documentation.
Also this example wont return undefined
when object's key
is array, unlike lodash.get
.
const get = (unit, path) => { if (path === "") { return unit; } const pathList = path.split("."); return Array.isArray(unit) ? get(unit[0], pathList.join(".")) : get(unit[pathList[0]], pathList.slice(1).join(".")); }; var test = { a: [{ b: { c: 3 } }] }; console.log(get(test, "a.b.c"));
Conclusion
This code is only for educational purpose. Edge cases are not covered here and it should not be used anywhere in production. So long.
Top comments (0)