用空值填充缺失的值

什么是最好的/最干净的解决scheme,find与unionObject相比在obj1中错过的字段,并添加值为null的缺失字段; 比如object1:

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

和unionObject是:

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

所以这里object1缺less带有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上是否有任何模块以干净的方式进行操作?

谢谢

这是一个简单的解决scheme。 它使用lodash,但不是绝对必要的。 您可以用它们的普通JS等价物replace_.isUndefined_.isPlainObject

 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>