用空填充缺失值

Filling missing values with null

本文关键字:填充      更新时间:2023-09-26

unionObject相比,找到obj1中缺少的那些字段并添加值为null的缺失字段的最佳/最干净的解决方案是什么;例如对象 1:

  var object1= { id: '123',
          name: 'test1'              
    }

而联合对象是:

  var unionObject = { id: '124',
          name: 'test2',
          type: 'type2',
          files: 
           {
             http: 'test12.com',
             https: 'test2.com' 
           }
    }

所以这里的 object1 缺少带有字段 http 和 https 和类型的文件;所以我想要的输出是:

 var desiredOutput= { id: '123',
          name: 'test1',
          type: null,
          files: 
           {
             http: null,
             https: null 
           }
    }

请注意,这不是我给出的输出:

 var notDesiredOutput= { id: '123',
          name: 'test1',
          type: null,
          files: null              
    }

在 Node.JS 中执行此操作的最佳/最干净方法是什么;NPM 上是否有任何模块可以以干净的方式执行此操作?

谢谢

这是一个简单的解决方案。它使用 lodash,但不是绝对必要的。您可以将_.isUndefined_.isPlainObject替换为它们的普通 JS 等效项。

function inferFromUnion(obj, union) {
  Object.keys(union).forEach(function(key) {
    if (_.isUndefined(obj[key])) {
      if (_.isPlainObject(union[key])) {
        obj[key] = {};
        inferFromUnion(obj[key], union[key]);
      } else {
        obj[key] = null;
      }
    }
  });
}
var unionObject = {
  id: '124',
  name: 'test2',
  type: 'type2',
  files: {
    http: 'test12.com',
    https: 'test2.com'
  }
};
var object1 = {
  id: '123',
  name: 'test1'
};
inferFromUnion(object1, unionObject);
console.log(object1);
document.write(JSON.stringify(object1));
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>