Skip to content

Instantly share code, notes, and snippets.

@bbagdad
Created April 26, 2018 09:20
Show Gist options
  • Save bbagdad/6764784602b8b84334bed9945434f41b to your computer and use it in GitHub Desktop.
Save bbagdad/6764784602b8b84334bed9945434f41b to your computer and use it in GitHub Desktop.
Object.prototye.getValue
/*
* Gets the value of the object by using the keys passed as string.
* Returns the value of the specified key, null if undefined.
*/
if (!Object.prototype.getValue) {
Object.prototype.getValue = function (key) {
var self = this;
if (!(self instanceof Object) || Object.keys(self).length == 0 || !key || typeof key !== 'string') {
return self;
}
if (key.indexOf('.') != -1) {
var subKey = key.substr(0, key.indexOf('.'));
if (self[subKey]) {
return self[subKey].getValue(key.substr(key.indexOf('.') + 1))
}
} else {
return self[key];
}
}
}
@bbagdad
Copy link
Author

bbagdad commented Apr 26, 2018

Usage Example :

var x = {
	a: {
		b: {
			c: {
				d: "ABC"
			},
			e: "ABC"
		},
		f: "AB"
	},
	g: "A"
};

x.getValue('a.b.c');

// returns {d: "ABC"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment