Advertisement
Guest User

Untitled

a guest
Apr 19th, 2014
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. var someObject = {
  2. 'part1' : {
  3. 'name': 'Part 1',
  4. 'txt': 'example',
  5. },
  6. 'part2' : {
  7. 'name': 'Part 2',
  8. 'size': '15',
  9. 'qty' : '60'
  10. },
  11. 'part3' : [
  12. {
  13. 'name': 'Part 3A',
  14. 'size': '10',
  15. 'qty' : '20'
  16. }, {
  17. 'name': '[value]',
  18. 'size': '5',
  19. 'qty' : '20'
  20. }, {
  21. 'name': 'Part 3C',
  22. 'size': '7.5',
  23. 'qty' : '20'
  24. }
  25. ]};
  26.  
  27. getPath(obj, '[value]');
  28.  
  29. function getPath(obj, val, path) {
  30. path = path || "";
  31. var fullpath = "";
  32. for (var b in obj) {
  33. if (obj[b] === val) {
  34. return (path + "/" + b);
  35. }
  36. else if (typeof obj[b] === "object") {
  37. fullpath = getPath(obj[b], val, path + "/" + b) || fullpath;
  38. }
  39. }
  40. return fullpath;
  41. }
  42.  
  43. console.log(getPath(testObj, '20')); // Prints: /part3/2/qty
  44. console.log(getPath(testObj, "[value]")); // Prints: /part3/1/name
  45.  
  46. function getPath(obj, value, path){
  47. path = path || [];
  48. if(obj instanceof Array || obj instanceof Object){
  49. //Search within children
  50. for(var i in obj){
  51. path.push(i); //push path, will be pop() if no found
  52. var subPath = getPath(obj[i], value, path);
  53. //We found nothing in children
  54. if(subPath instanceof Array){
  55. if(subPath.length == 1 && subPath[0]==i){
  56. path.pop();
  57. }
  58. //We found something in children
  59. }else if(subPath instanceof Object){
  60. path = subPath;
  61. break;
  62. }
  63. }
  64. }else{
  65. //Match ?
  66. if(obj == value){
  67. return {finalPath:path};
  68. }else{
  69. //not ->backtrack
  70. path.pop();
  71. return false;
  72. }
  73. }
  74. return path;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement