开发者

Need Comparison of Object of same type to know the difference in javascript

I need to compare the object to know what properties are changed and what properties are added new. Is there any code snippet which will loop through entire object and its properties and alert if any changes exist and continue its process till the end.

Consider i need to compare the gri开发者_如何转开发dpanel(object) in extjs before and after show and hide event of its parent panel.

Thanks in advance


If you simply want to check if two objects of the same class differ:

function differ(a, b) {
  for (var i in a) {
    if (a.hasOwnProperty(i) && b.hasOwnProperty(i) && a[i] === b[i]) {
      return true;
    }
  }
  return false;
}

a = {foo: 1, bar: 2};
b = {bar: 2};

alert( differ(a, b) ? "Objects differ" : "Objects are the same" );

If that's not what you're after, explain your problem in more detail.


I had a similar problem when I was adding objects to an array. I wanted to be sure, that the same object is not added twice.

I found a helper function for ExtJS which implements a function that compares objects based on the values contained by the object:

https://github.com/nmishra/helpers.js

It then can be used like this:

var obj1 = {foo: 'bar'},
    obj2 = {foo: 'bar'},
    equality = Ext.ux.util.Object.compareObject(obj1, obj2);
console.log(equality);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜