使用null填充缺失值

时间:2014-12-16 01:52:43

标签: javascript node.js asynchronous lodash

与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缺少字段为http和https并且键入的文件;所以我想要的输出是:

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

请注意,这不是我的deiredoutput:

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

Node.JS中最好/最干净的方法是什么? NPM上是否有任何模块以干净的方式进行?

由于

1 个答案:

答案 0 :(得分:1)

这是一个简单的解决方案。它使用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>
&#13;
&#13;
&#13;

相关问题