javascriptobject-comparison

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


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 lodash, but it appears to perform a deep comparison which I don't want to do.

var a = { x: 1, y: 2}
var b = { x: 1, y: 3}

Is there some way for example to compare a and b?


Solution

  • 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:


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