【问题标题】:Loosely searching an associative array for the presence of nested elements松散地搜索关联数组以查找嵌套元素的存在
【发布时间】:2015-04-20 22:33:01
【问题描述】:

考虑下面的关联数组:

{
"body": [
    {
        "key1": "value1",
        "body2": {
            "key2": "value2"
        }
    }
 ]
}

如何搜索这个数组的粗略结构?例如,我怎么能说array[key1] 低于array[key2]?如果措辞不正确,我深表歉意。

【问题讨论】:

  • 你不能,至少在你创建了诸如搜索objects之前不能!

标签: javascript arrays search


【解决方案1】:

工作小提琴:http://jsfiddle.net/4gy417o7/1/

objLevels = [];

function assignLevel(obj,level){

        var tempArr = objLevels[level] || [];

        for(var p in obj){
                if(obj.hasOwnProperty(p)) 
                        tempArr.push(p);

                if(typeof obj[p]=='object')
                        assignLevel(obj[p],(level+1));

                objLevels[level] = tempArr;
        }
}

assignLevel(yourObj,1);
console.log(objLevels);

通过使用原始对象和 level=1 启动递归函数 assignLevel,您最终应该得到一个对象数组 (objLevels),其中每个对象的键是嵌套级别,值是一个数组对象中处于该嵌套级别的键。

所以 objLevels 会是这样的

[
   {1: ["body"] },
   {2: [0] }, // this is because body is an array, and the object inside it is at index 0
   {3: ["key1","body1"] },
   {4: ["key2] }
]

然后您基本上可以找到任何特定的key 变量的嵌套级别,如下所示:

function getKeyLevel(key){
        for(var level in objLevels)
                if(objLevels[level].indexOf(key) > -1)
                       return level;

        return false;
}
console.log(getKeyLevel("key2")) // 4
console.log(getKeyLevel("key1")) // 3

【讨论】:

    【解决方案2】:

    你应该能够使用递归函数来做到这一点,比如

    function searchObject(object, level, parent){
        // If the parent is omitted, we're at the start of the search.
        var obj = object[parent] || object;
        // For every key of the object supplied...
        Object.keys(obj).forEach(
            function(key){
                alert(key+" found at level "+level+".");
                // Check if object exists, then if it is of type Object
                if(obj[key] !== undefined && obj[key].toString() === "[object Object]"){
                    // Search the object at a lower level
                    searchObject(obj[key], level+1, key);
                }
            }
        );
    }
    

    Here's a fiddle 正在展示它。

    玩得开心!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 2014-01-02
      • 1970-01-01
      • 2017-04-12
      • 2021-08-27
      • 1970-01-01
      相关资源
      最近更新 更多