Skip to content

Instantly share code, notes, and snippets.

@shmaltorhbooks
Created May 23, 2017 06:47
Show Gist options
  • Save shmaltorhbooks/2a8b3e652f11fe2a395310abe79e2d48 to your computer and use it in GitHub Desktop.
Save shmaltorhbooks/2a8b3e652f11fe2a395310abe79e2d48 to your computer and use it in GitHub Desktop.
get object property by path
Object.getValue = function(obj, path) {
if (typeof obj === 'undefined' || obj === null) return;
path = path.split(/[\.\[\]\"\']{1,2}/);
for (let i = 0, l = path.length; i < l; i += 1) {
if (path[i] !== '') {
obj = obj[path[i]];
if (typeof obj === 'undefined' || obj === null) {
return;
}
}
}
return obj;
}
var user = {name: 'John', address: [{street: 'River Ave'}]};
Object.getValue(user, 'address[0].street'); // River Ave
Object.getValue(user, 'occupation[9].company'); // null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment