Search code examples
javascriptobjectencapsulation

JS find key value pair in encapsulated object


I have a big problem and I need your help.

I have a object like this:

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

and I want to search for the key "folderid = 3" and find the object.

How can I do this in JavaScript?

Kind regards and thanks for your help


Solution

  • I came to a more generalised solution, that supports multiple properties check:

        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;
            }
        }
    

    demo: http://jsfiddle.net/dzs1orbw/