JS在封装对象中查找键值对

JS find key value pair in encapsulated object

我有一个大问题,我需要你的帮助。

我有一个这样的对象:

{
    folder1: {
        folderid: 1,
        files: {
            name: "yeah.txt"
        },
        folder2: {
            folderid: 2
            folder3: {
                folderid: 3
            }
        }
    },
    folder4: {
        folderid: 4
    }
}

我想搜索键 "folderid = 3" 并找到对象。

如何在 JavaScript 中执行此操作?

谨致问候并感谢您的帮助

您可以使用 DSF algorithm to do this: http://jsfiddle.net/L5b07bt6/

var obj = {
    folder1: {
        folderid: 1,
        files: {
            name: "yeah.txt"
        },
        folder2: {
            folderid: 2,
            folder3: {
                folderid: 3,
                caption: "I got it!"
            }
        }
    },
    folder4: {
        folderid: 4
    }
};

function find(root, id) {
    if (root.folderid == id) return root;
    if (typeof root !== 'object') return null;
    var key, val;
    for (key in root) {
        val = find(root[key], id);
        if (val != null) return val;
    }
    return null;
}

var result = find(obj, 3);
if (!result) alert("Not found!");
else alert("Found: " + result.caption);

我找到了一个更通用的解决方案,它支持多个属性检查:

    function search(obj, properties){
        if(Object.keys(properties).every(function(key){
            return obj[key] === properties[key];
        })) {
            return obj;
        } else {
            Object.keys(obj).forEach(function(key){
                var child = obj[key];
                if(child !== null && typeof child === 'object'){                
                    return search(child, properties);
                }
            });
            return false;
        }
    }

演示:http://jsfiddle.net/dzs1orbw/

还有一个:

function findByKey (object, searchKey){
    if(typeof object !== 'object'){
        return false;
    }

    for(var key in object){
        if(object[key] === searchKey){
            return object;
        } else {
            if(typeof (object[key] === 'object')){
                var result = findByKey(object[key], searchKey);
                if(result){
                    return result;
                }
            } 
        }
    }
}

http://jsfiddle.net/mattposch/ebmd8xtk/