Object Comparing: check if an object contains the whole other object

前端 未结 5 669
日久生厌
日久生厌 2021-01-18 19:51

I have two objects. Their structure looks a bit like this:

{
 education: [\"school\", \"institute\"],
 courses: [\"HTML\", \"JS\", \"CSS\"],
 Computer: {
            


        
5条回答
  •  再見小時候
    2021-01-18 20:16

    JavaScript (in ES5) has two composite native types (I'm assuming you don't have any custom collections in your code, if you do - I assume they support the 'old' iteration protocol (having .length)

    Here is an annotated sketch of a solution. I did not run this - it's there to get you an idea of how to implement this algorithm. Note that this enters an endless loop for back references (var a = {}; a.a =a}).

    function sub(big,small){
        if(typeof big === "function") return small === big; // function reference equality.
        if(big.length){ // iterable, for example array, nodelist etc. (even string!)
            if(small.length > big.length) return false; // small is bigger!
            for(var i = 0; i < small.length; i++ ){
                if(!sub(big[i],small[i])){ // doesn't have a property
                    return false;
                }
            }
            return true; // all properties are subproperties recursively
        }
        if(typeof big === "object" && big !== null){
            // I assume null is not a subset of an object, you may change this, it's conceptual
            if(typeof small !== "object" || small === null) return false; 
            for(var key in small){
                // I consider the prototype a part of the object, you may filter this with a 
                // hasOwnProperty check here.
                if(!sub(big[key],small[key])){ // doesn't have a property
                     return false;
                }
                return true;
            }
        }
        return big === small; // primitive value type equality
                              // , or ES7 value type equality, future compat ftw :P
    }
    

提交回复
热议问题