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

时间:2015-03-20 12:02:51

标签: javascript object encapsulation

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

我有一个这样的对象:

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

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

我如何在JavaScript中执行此操作?

亲切的问候并感谢您的帮助

3 个答案:

答案 0 :(得分:2)

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

    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/

答案 1 :(得分:1)

您可以使用DSF算法执行此操作: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);

答案 2 :(得分:1)

又来了另一个:

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/