Created
April 21, 2018 21:22
-
-
Save Archakov06/9a65a7f4361b883bb26d9e77dda0d20c to your computer and use it in GitHub Desktop.
Lodash like _.get() function
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
const obj = { | |
a: { | |
b: { | |
c: 1 | |
} | |
}, | |
user: { | |
id: { | |
bbb: 123 | |
}, | |
files: [ | |
{name: 'Bashir'}, | |
{name: 'Umar'}, | |
{name: 'Ilez'}, | |
] | |
} | |
}; | |
function getValue(obj, path) { | |
var keys = path.split('.'); | |
var value = obj; | |
var arrKey, key, i = 0; | |
while (value && Object.keys(value).indexOf(keys[i] && keys[i].replace(/\[(.*)\]/, '')) >= 0) { | |
key = keys[i].replace(/\[(.*)\]/, ''); | |
value = value[key]; | |
arrKey = keys[i++].match(/\[(.*)\]/); | |
if (Array.isArray(value) && arrKey) { | |
key = parseInt(arrKey[1]); | |
value = value[key]; | |
} | |
} | |
return value; | |
} | |
console.log(getValue(obj, 'a.b.c')); // 1 | |
console.log(getValue(obj, 'user.id.bbb')); // 123 | |
console.log(getValue(obj, 'user.files[2].name')); // Ilez |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment