Find by key deep in a nested array

后端 未结 17 1496
礼貌的吻别
礼貌的吻别 2020-11-22 15:41

Let\'s say I have an object:

[
    {
        \'title\': \"some title\"
        \'channel_id\':\'123we\'
        \'options\': [
                    {
                 


        
17条回答
  •  旧时难觅i
    2020-11-22 16:00

    Improved answer to take into account circular references within objects. It also displays the path it took to get there.

    In this example, I am searching for an iframe that I know is somewhere within a global object:

    const objDone = []
    var i = 2
    function getObject(theObject, k) {
        if (i < 1 || objDone.indexOf(theObject) > -1) return
        objDone.push(theObject)
        var result = null;
        if(theObject instanceof Array) {
            for(var i = 0; i < theObject.length; i++) {
                result = getObject(theObject[i], i);
                if (result) {
                    break;
                }   
            }
        }
        else
        {
            for(var prop in theObject) {
                if(prop == 'iframe' && theObject[prop]) {
                    i--;
                    console.log('iframe', theObject[prop])
                    return theObject[prop]
                }
                if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) {
                    result = getObject(theObject[prop], prop);
                    if (result) {
                        break;
                    }
                } 
            }
        }
        if (result) console.info(k)
        return result;
    }
    

    Running the following: getObject(reader, 'reader') gave the following output and the iframe element in the end:

    iframe // (The Dom Element)
    _views
    views
    manager
    rendition
    book
    reader
    

    NOTE: The path is in reverse order reader.book.rendition.manager.views._views.iframe

提交回复
热议问题