object-patch.js 654 B

12345678910111213141516171819202122
  1. // Adds Object.get function
  2. // +pathstr+ is a string of dot-separated nested properties on +ojb+
  3. // returns undefined if any of the properties do not exist
  4. // returns the value of the last property otherwise
  5. //
  6. // Object.get({"foo": {"bar": 123}}, "foo.bar"); // 123
  7. // Object.get({"foo": {"bar": 123}}, "bar.foo"); // undefined
  8. Object.get = function(obj, pathstr) {
  9. var path = pathstr.split(".");
  10. var result = obj;
  11. for (var i = 0; i < path.length; i++) {
  12. var key = path[i];
  13. if (!result || !Object.prototype.hasOwnProperty.call(result, key)) {
  14. return undefined;
  15. } else {
  16. result = result[key];
  17. }
  18. }
  19. return result;
  20. };