Created
May 23, 2017 06:47
-
-
Save shmaltorhbooks/2a8b3e652f11fe2a395310abe79e2d48 to your computer and use it in GitHub Desktop.
get object property by path
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
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