Compare two objects properties in JS

烂漫一生 提交于 2020-05-09 06:01:06

问题


I need to compare two objects, and find out what properties are missing. The objects are fairly big, with several levels.

I will give short example of the type of object:

    UC = {};
    UC.start = {}
    UC.start.enableHardEccDecline = '';
    UC.start.template = {};
    UC.start.template.ecc = '';
    UC.start.template.decline = {};
    UC.start.template.decline.title = '';
    UC.start.template.decline.body = '';
    UC.general = {};...

So this is an example object. What I need to compare is just the properties. I do not care for the value. I will be comparing this object with another one very similar, but some properties might be missing.


回答1:


function compare(base, compared, deepSearch) {
  var missing = [];

  var compareProp = function (baseValue, comparedValue, path, deepSearch) {
    //console.log('comparing', path.join('.'));

    if (comparedValue === undefined) {
      console.log('missing key', path.join('.'));

        if (!deepSearch) {
          return;
        }
    }

    if (typeof baseValue === 'object') {
      Object.keys(baseValue).forEach(function (key) {
        compareProp(baseValue [key], comparedValue && comparedValue [key], path.concat(key), deepSearch);
      }); 
    }
  };

  Object.keys(base).forEach(function (key) {
    compareProp(base [key], compared [key], [key], deepSearch);
  });
}

UC = {};
UC.start = {}
UC.start.enableHardEccDecline = '';
UC.start.template = {};
UC.start.template.ecc = '';
UC.start.template.decline = {};
UC.start.template.decline.title = '';
UC.start.template.decline.body = '';
UC.general = {};

compare (UC, {}, true);



回答2:


I have just made a quick example here, not sure exactly how you want to apply this, but I have added the missing items to an array, which is logging it.

Obj1 should be your standard comparison object, obj2 the one received from request.

var obj1 = {};
obj1.test1 = 0;
obj1.test2 = 0;
obj1.test2222 = 0;
obj1.testLoremIpsum = 0;
obj1.lalala = 0;

var obj2 = {};
obj2.test1 = 0;
obj2.test25 = 0;
obj2.lalala1 = 0;

var k , i = 0;
var missingProps = [];

for( i in obj1 )
{
    var isFound = false;
    for( k in obj2) if( i == k ) isFound = true;
    if(!isFound) missingProps.push( i );
}
console.log(missingProps);



回答3:


How about use JSON.stringify to convert object to string, then do the string comparison:

JSON.stringify(UC) === JSON.stringify(UCToBeCompared)

By using this method, you have to make sure the objects don't have circular reference, otherwise JSON.stringify would throw an exception




回答4:


I have a made a example here. Hope it resolves your issue. It will compare Object KEYS only and return the object key which is not exist with compared object.

var a = Object.keys(obj1);
var b = Object.keys(obj2);

var missing= a.filter(function(v){
    return b.indexOf(v)==-1;
})

console.log(missing);



回答5:


If your situation allows it I'd suggest using http://underscorejs.org/ library, rather than rolling your own solution (or go look at their implementation). In JS deep object comparison is sometimes not trivial. If you decide to roll your own solution, you would recursively iterate through the properties and compare them one by one (ignoring native / built-in object properties and perhaps inherited from some prototype).

I'll gladly elaborate if you'd like.



来源:https://stackoverflow.com/questions/46059200/compare-two-objects-properties-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!