-
-
Save rkalkani/3e5b87cc6e26cde623c6cf2cb40aa15b to your computer and use it in GitHub Desktop.
Adding string with dot-notation as a key to JavaScript objects
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
// Be careful when changing Object's prototype to avoid overwriting of methods | |
if (Object.prototype.setPath === undefined && Object.prototype.getPath === undefined) { | |
Object.prototype.setPath = function (path, value, notation) { | |
function isObject(obj) { return (Object.prototype.toString.call(obj) === '[object Object]' && !!obj);} | |
notation = notation || '.'; | |
path.split(notation).reduce(function (prev, cur, idx, arr) { | |
var isLast = (idx === arr.length - 1); | |
// if <cur> is last part of path | |
if (isLast) return (prev[cur] = value); | |
// if <cur> is not last part of path, then returns object if existing value is object or empty object | |
return (isObject(prev[cur])) ? prev[cur] : (prev[cur] = {}); | |
}, this); | |
return this; | |
}; | |
Object.prototype.getPath = function(path, notation) { | |
notation = notation || '.'; | |
return path.split(notation).reduce(function(prev, cur) { | |
return (prev !== undefined) ? prev[cur] : undefined; | |
}, this); | |
}; | |
} | |
// how to use | |
var config = {}; | |
config.setPath('db.common.credentials', {login: 'root', pass: ''}); | |
config.setPath('db.host.dev', 'localhost'); | |
config.setPath('db|host|prod', 'prodhost', '|'); | |
console.log(config.getPath('db.host')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment