Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. /**
  2. * Extract nested property from object. If nested property cannot be reached, return value of rescue
  3. * @param obj Object
  4. * @param path Can be dot-separated string or array
  5. * @param rescue (optional) default value. Defaults to null
  6. */
  7. function extract(obj, path, rescue){
  8.  
  9. if (typeof obj === "object" && path){
  10.  
  11. var elements = typeof path === "string" ? path.split(".") : path;
  12.  
  13. if (typeof elements.shift === "function"){
  14.  
  15. var head = elements.shift();
  16.  
  17. if (obj.hasOwnProperty(head)){
  18.  
  19. return (elements.length === 0) ? obj[head] : extract(obj[head], elements, rescue);
  20.  
  21. } // if
  22.  
  23. } // if
  24.  
  25. } // if
  26.  
  27. return rescue || null;
  28.  
  29. } // extract
  30.  
  31.  
  32. var noob = {k1 : {k11 : {k111 : "v1"}}, k2 : { k21 : "v2"}};
  33.  
  34. console.log(extract(noob, 'k1.k11')); // {k111 : "v1"}
  35. console.log(extract(noob, 'k1.k11.k111')); // v1
  36. console.log(extract(noob, ['k1', 'k11', 'k111'])); // v1
  37. console.log(extract(noob, 'k1.k11.kx')); // null
  38. console.log(extract(noob, 'k2')); // k2 : { k21 : "v2"}
  39. console.log(extract(noob, 'k2.k21.k22')); // null
  40. console.log(extract(noob, 'k1.k11.k22', "ZUT")); // ZUT
  41. console.log(extract(noob, '', "ZUT")); // ZUT
  42. console.log(extract(false, '', "ZUT")); // ZUT
  43.  
  44. var x = {
  45. blah: {
  46. blam: "bloo"
  47. }
  48. }
  49. with(x) {
  50. console.log(blah)
  51. }
  52. with(x){
  53. console.log(blah.blam)
  54. }
  55.  
  56. var extract = function(obj, path, rescue){
  57. with(obj) {
  58. return eval(path) || rescue;
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement