Find by key deep in a nested array

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

Let\'s say I have an object:

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


        
17条回答
  •  眼角桃花
    2020-11-22 15:44

    Another recursive solution, that works for arrays/lists and objects, or a mixture of both:

    function deepSearchByKey(object, originalKey, matches = []) {
    
        if(object != null) {
            if(Array.isArray(object)) {
                for(let arrayItem of object) {
                    deepSearchByKey(arrayItem, originalKey, matches);
                }
            } else if(typeof object == 'object') {
    
                for(let key of Object.keys(object)) {
                    if(key == originalKey) {
                        matches.push(object);
                    } else {
                        deepSearchByKey(object[key], originalKey, matches);
                    }
    
                }
    
            }
        }
    
    
        return matches;
    }
    

    usage:

    let result = deepSearchByKey(arrayOrObject, 'key'); // returns an array with the objects containing the key
    

提交回复
热议问题