Skip to content

Instantly share code, notes, and snippets.

@rkalkani
Forked from likerRr/dot-notation-object.js
Created July 18, 2016 11:11
Show Gist options
  • Save rkalkani/3e5b87cc6e26cde623c6cf2cb40aa15b to your computer and use it in GitHub Desktop.
Save rkalkani/3e5b87cc6e26cde623c6cf2cb40aa15b to your computer and use it in GitHub Desktop.
Adding string with dot-notation as a key to JavaScript objects
// 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