how to get the path of an object's value from a value in javascript

前端 未结 3 763
清歌不尽
清歌不尽 2021-01-23 08:46

Example:

var someObject = {
\'part1\' : {
    \'name\': \'Part 1\',
    \'txt\': \'example\',
},
\'part2\' : {
    \'name\': \'Part 2\',
    \'size\': \'15\',
           


        
3条回答
  •  迷失自我
    2021-01-23 09:09

    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);
          }
          else if (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
    

提交回复
热议问题