How can I do a shallow comparison of the properties of two objects with Javascript or lodash?

后端 未结 8 1924
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 11:31

Is there a way I can do a shallow comparison that will not go down and compare the contents of objects inside of objects in Javascript or lodash? Note that I did check lodas

8条回答
  •  失恋的感觉
    2021-01-01 12:19

    function areEqualShallow(a, b) {
        for(var key in a) {
            if(!(key in b) || a[key] !== b[key]) {
                return false;
            }
        }
        for(var key in b) {
            if(!(key in a) || a[key] !== b[key]) {
                return false;
            }
        }
        return true;
    }
    

    Notes:

    • Since this is shallow, areEqualShallow({a:{}}, {a:{}}) is false.

    • areEqualShallow({a:undefined}, {}) is false.

    • This includes any properties from the prototype.

    • This uses === comparison. I assume that is what you want. NaN === NaN is one case that may yield unexpected results. If === is not what you want, substitute with the comparison you want.


    EDIT: If the same keys are in each object, then

    function areEqualShallow(a, b) {
        for(var key in a) {
            if(a[key] !== b[key]) {
                return false;
            }
        }
        return true;
    }
    

提交回复
热议问题