如何获取导致JavaScript对象中给定键/值的路径?

时间:2014-06-12 07:33:07

标签: javascript json node.js

我环顾四周,但没有找到解决这个问题的方法:
我试图获得导致给定密钥或值的完整路径(密钥列表)(考虑帐户欺骗)。
我知道它类似于这个问题: how to get the path of an object's value from a value in javascript
但你可能会发现不同的方式:
- 按键
- 按价值
- 如果存在任何欺骗,它应该返回所有可能性的数组 一个简短的例子是说话而不是长篇演说:

示例代码:

var data = {
    "key1": {
        "key1SubKey1": {
            "key1SubSubKey1": "key1SubSubKey1_value"
        },
        "key1SubKey2": {
            "key1SubSubKey2": "key1SubSubKey2_value"
        },
        "key1SubKey3": {
            "key1SubSubKey3": "key1SubSubKey3_value"
        },
        "duplicatedKey": "duplicated_value"
    },
    "key2": {
        "key2SubKey1": {
            "key2SubSubKey1": "key2SubSubKey1_value"
        },
        "key2SubKey2": {
            "key2SubSubKey2": "key2SubSubKey2_value"
        },
        "key2SubKey3": {
            "key2SubSubKey3": "key2SubSubKey3_value"
        },
        "duplicatedKey": "duplicated_value"
    }
}

用法示例

按价值搜索

getPathFromValue (data, "key2SubSubKey1_value") ;
// This should return : data['key2']['key2SubKey1']['key2SubSubKey1']

getPathFromValue (data, "duplicated_value") ;
// [ data['key1']['duplicatedKey'], data['key2']['duplicatedKey'] ]

按键搜索

getPathFromKey (data, "key2SubSubKey1") ;
// data['key2']['key2SubKey1']

getPathFromKey (data, "duplicatedKey") ;
// [ data['key1'], data['key2'] ]

1 个答案:

答案 0 :(得分:0)

请尝试以下方法:

    function findValue(data, value,path){
    if(typeof(data) != "object" || Object.keys(data).length == 0) 
        return { "path" : "" , "value" : ""};

    for(var prop in data)  { 
     if (data[prop] == value) 
        return { "path" :  path + "['" + prop + "']" , "value" : value};
    }


    for(var prop in data) { 
        var result = findValue(data[prop],value,path === undefined ? "['" + prop + "']" : path + "['" + prop + "']" );

        if (typeof(result) !== typeof(undefined) && result.value != "") { 
            return result; 
        }
    }
}

执行var result = findValue(data,“key1SubSubKey1_value”)将导致对象具有属性:value和path。

获取路径只访问result.path。