Posted By

Pjotor on 08/12/14


Tagged

json


Versions (?)

JSON byPath


 / Published in: JavaScript
 

URL: http://pjotor.com

Use dot notation string as path to access deep JSON keys:

test.deep.deeper.key.childObject.branch.child === test.byPath("deep.deeper.key.childObject.branch.child")

  1. //As function
  2. function byPath(path, ob) {
  3. return path
  4. .split(".")
  5. .reduce(function(a, b){
  6. return a instanceof Object && a[b] instanceof Object?
  7. a[b] : typeof a[b] ==="string" ? a[b] : ob[a][b];
  8. });
  9. }
  10.  
  11. //As prototype
  12. Object.prototype.byPath = function(path){
  13. var self = this;
  14. return path
  15. .split(".")
  16. .reduce(function(a, b){
  17. return a instanceof Object && a[b] instanceof Object?
  18. a[b] : typeof a[b] ==="string" ? a[b] : self[a][b];
  19. });
  20. }

Report this snippet  

You need to login to post a comment.