【问题标题】:How to get the path leading to given key / value in JavaScript object?如何获取通向 JavaScript 对象中给定键/值的路径?
【发布时间】:2014-06-12 07:33:07
【问题描述】:

我环顾四周,但没有找到解决这个问题的方法:
我正在尝试获取导致给定键或值的完整路径(键列表)(考虑到欺骗)。
我知道它类似于这个问题: 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'] ]

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 到目前为止我有这个jsfiddle.net/u2dK3,它肯定可以改进;)。我只从值中获取路径,而不是从键中...

标签: javascript json node.js


【解决方案1】:

请尝试以下方法:

    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") 将产生一个具有以下属性的对象:值和路径。

要获取路径,只需访问 result.path。

【讨论】:

  • var thePath = findValue(data,"key2SubSubKey3_value") ; 给我:InternalError: too much recursion ?
  • 您在此处发布的数据对象上尝试过吗?我又试了一次,效果很好。该错误听起来像是在具有更多级别的对象上迭代。
  • 在我的: • 这有效:var thePath = findValue(data,"key1SubSubKey1_value") • 这不:var thePath = findValue(data, 'key2SubSubKey1_value') ; var thePath = findValue(data,"key2SubSubKey3_value") 在 Chrome 上我得到:“RangeError: Maximum call stack size exceeded
猜你喜欢
  • 2021-11-27
  • 2014-10-13
  • 2014-05-24
  • 2012-04-12
  • 2014-02-20
  • 2012-07-20
  • 2021-12-25
相关资源
最近更新 更多