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

前端 未结 5 723
日久生厌
日久生厌 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:12

    In addition to Benjamin's answer - you could test this:

    const sub = (big, small) => {
        if (typeof big === 'function' || typeof small === 'string') return small === big; // function or string reference equality
        if (big && big.length) { // iterable, for example array, nodelist etc. (even string!)
            if (small.length > big.length) return false; // small is bigger!
            for (let 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;
            // console.log(Object.keys(small));
            for (const key of Object.keys(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]) === false) // doesn't have a property
                    return false;
                continue;
            }
            return true;
        }
        return big === small; // primitive value type equality
    };
    

    or even use a much cleaner solution: https://github.com/blackflux/object-deep-contain

提交回复
热议问题