Compare two objects properties in JS

后端 未结 5 1876
面向向阳花
面向向阳花 2021-01-21 13:56

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

5条回答
  •  感情败类
    2021-01-21 14:42

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

提交回复
热议问题