Find by key deep in a nested array

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

Let\'s say I have an object:

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


        
17条回答
  •  攒了一身酷
    2020-11-22 16:00

    Recursion is your friend. I updated the function to account for property arrays:

    function getObject(theObject) {
        var result = null;
        if(theObject instanceof Array) {
            for(var i = 0; i < theObject.length; i++) {
                result = getObject(theObject[i]);
                if (result) {
                    break;
                }   
            }
        }
        else
        {
            for(var prop in theObject) {
                console.log(prop + ': ' + theObject[prop]);
                if(prop == 'id') {
                    if(theObject[prop] == 1) {
                        return theObject;
                    }
                }
                if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) {
                    result = getObject(theObject[prop]);
                    if (result) {
                        break;
                    }
                } 
            }
        }
        return result;
    }
    

    updated jsFiddle: http://jsfiddle.net/FM3qu/7/

提交回复
热议问题