Skip to content

Instantly share code, notes, and snippets.

@Archakov06

Archakov06/get.js

Created Apr 21, 2018
Embed
What would you like to do?
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