0

I have 2 objects, one of which starts as a copy of the other. I would like to be able to check if a different values have changed i.e. that they no longer match:

var obj = {
    key1: {
        innerKey: "val"
    },
    key2: "matching val"
};

var copy = {
    key1: {
        innerKey: "non-matching val"
    },
    key2: "matching val"
};

I would like to have some sort of hasChanged() method which would work something as follows:

hasChanged(obj.key1.innerKey); // result true
hasChanged(obj.key2); // result false

It seems I need some way to get the "path" or location of the property in order to find that property on the other object for comparison, but I'm not sure how to go about doing that.

Thanks

3
  • 1
    I think you'll have to pass three args: hasChanged(obj1, obj2, "key1.innerKey"). Then, you can look for that property on both objects by parsing it into it's pieces and looking it up on both objects. Commented Jul 27, 2015 at 8:10
  • 1
    You may be interested in Object.observe developer.mozilla.org/pl/docs/Web/JavaScript/Reference/… Commented Jul 27, 2015 at 8:13
  • @joe Please try my answer below. Commented Jul 27, 2015 at 9:28

2 Answers 2

1

 $.fn.hasChanged = function(obj,key){
   var origObj = this[0];
   
   var originalValue = Object.byString(origObj,key);
    var currentValue = Object.byString(obj,key);
   return !(originalValue == currentValue);
  
};
     
Object.byString = function(o, s) {
    s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
    s = s.replace(/^\./, '');           // strip a leading dot
    var a = s.split('.');
    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];
        if (k in o) {
            o = o[k];
        } else {
            return;
        }
    }
    return o;
}



var obj = {
    key1: {
        innerKey: "val"
    },
    key2: "matching val"
};

var copy = {
    key1: {
        innerKey: "non matching val"
    },
    key2: "matching val"
};
alert($(obj).hasChanged(copy,'key1.innerKey'));
alert($(obj).hasChanged(copy,'key2'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer @bipashant. v. interesting.
1

It looks like the lodash library has just what I'm looking for here:

_.get(obj, path);

e.g. _.get(obj, 'key1.innerKey'); // "val"

so:

function hasChanged(obj, backup, path) {
    var objVal = _.get(obj, path);
    var backupVal = _.get(backup, path);
    return objVal !== backupVal;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.