比较JS中两个对象的属性 [英] Compare two objects properties in JS

查看:42
本文介绍了比较JS中两个对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要比较两个对象,并找出缺少哪些属性.对象相当大,有几个层次.

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.

推荐答案

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

这篇关于比较JS中两个对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆