Skip to content Skip to sidebar Skip to footer

How To Get The Path Of An Object's Value From A Value In Javascript

Example: var someObject = { 'part1' : { 'name': 'Part 1', 'txt': 'example', }, 'part2' : { 'name': 'Part 2', 'size': '15', 'qty' : '60' }, 'part3' : [ {

Solution 1:

Here's some code that should get you a path to your object, not sure how super safe it is:

function getPath(obj, val, path) {
   path = path || "";
   var fullpath = "";
   for (var b in obj) {
      if (obj[b] === val) {
         return (path + "/" + b);
      }
      elseif (typeof obj[b] === "object") {
         fullpath = getPath(obj[b], val, path + "/" + b) || fullpath;
      }
   }
   return fullpath;
}

Where testObj is the object in your example:

console.log(getPath(testObj, '20'));      // Prints: /part3/2/qty
console.log(getPath(testObj, "[value]")); // Prints: /part3/1/name

Solution 2:

Try this:

http://jsfiddle.net/n8d2s/1/

The method returns an object, that contains the parts.

functiongetPath(obj, value, path){
    path = path || [];   
    if(obj instanceofArray || obj instanceofObject){
        //Search within childrenfor(var i in obj){
           path.push(i); //push path, will be pop() if no foundvar subPath = getPath(obj[i], value, path);
            //We found nothing in childrenif(subPath instanceofArray){
                if(subPath.length == 1 && subPath[0]==i){
                  path.pop();   
                }
            //We found something in children
            }elseif(subPath instanceofObject){
               path = subPath;                
               break;   
            }
        }
    }else{
        //Match ?if(obj == value){            
            return {finalPath:path};   
        }else{
            //not ->backtrack
            path.pop();
            returnfalse;   
        }
    } 
    return path;
}

Maybe its not the best code, took me 10min there but it should work.

To see any result, check your dev console F12.

Solution 3:

If you try this on the window object you'll end up in trouble as it is self referential. Quick and easy way to get around this is to a depth check:

  function getPath(obj, val, path, depth) {
     if (!depth) depth = 0;
     if (depth > 50) return'';
     path = path || "";
     var fullpath = "";
     for (var b in obj) {
        if (obj[b] === val) {
           return (path + "/" + b);
        }
        elseif (typeof obj[b] === "object") {
           fullpath = getPath(obj[b], val, path + "/" + b, depth++) || fullpath;
        }
     }
     return fullpath;
  }

This will return the same kind of path as above:

/part3/2/qty

To make that into an actual reference to variable simply regex:

'window' + '/part3/2/qty'.replace(/\/([0-9]+)\//g, '[$1].').replace(/\//g, '.')

Post a Comment for "How To Get The Path Of An Object's Value From A Value In Javascript"