Created
November 15, 2020 14:39
-
-
Save farskid/7d01aaf472b64ebf1e6f7a59b3dfb360 to your computer and use it in GitHub Desktop.
Lodash get in pure Javascript
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
function get(obj, path) { | |
const steps = path.split('.'); | |
return steps.reduce((result, step) => { | |
const isArrayItem = /\[\d+\]/.test(step); | |
if (isArrayItem) { | |
const [_, prop, index] = step.match(/^(.+)\[(\d+)\]$/) | |
return get(result, `${prop}.${index}`); | |
} | |
return result[step]; | |
}, obj); | |
} | |
/* | |
const obj = { | |
uuid: 'askldjlkasjdlkas', | |
user: { | |
name: 'John Doe', | |
loginHistory: [ | |
{at: '01.02.2020'}, | |
{at: '14.12.2019'} | |
] | |
} | |
} | |
console.log(get(obj, 'uuid')) // 'askldjlkasjdlkas' | |
console.log(get(obj, 'user.name')) // 'John Doe' | |
console.log(get(obj, 'user.loginHistory[1]')) // {at: '14.12.2019'} | |
const object = { 'a': [{ 'b': { 'c': 3 } }] }; | |
console.log(get(object, 'a[0].b.c')) // 3 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment