简体   繁体   中英

Loosely searching an associative array for the presence of nested elements

Consider the associative array below:

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

How can I search the rough structure of this array? For example, how can I say is array[key1] lower than array[key2] ? I apologize if this is not worded correctly.

Working fiddle: 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);

By initiating the recursive function assignLevel with your original object and level=1, you should end up with an array of objects ( objLevels ), in which each object's key is the nesting level, and value is an array of the keys in your object that are at that nesting level.

So objLevels will be something like

[
   {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] }
]

Then you can basically find any particular key variable's nesting level like so:

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

You should be able to do this using a recursive function, something like

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 showing it in action.

Have fun!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM