Skip to content

Instantly share code, notes, and snippets.

@Archakov06
Created April 21, 2018 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Archakov06/9a65a7f4361b883bb26d9e77dda0d20c to your computer and use it in GitHub Desktop.
Save Archakov06/9a65a7f4361b883bb26d9e77dda0d20c to your computer and use it in GitHub Desktop.
Lodash like _.get() function
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