user385729
user385729

Reputation: 1984

Filling missing values with null

What is the best/cleanest solution to find those fields that are being missed in obj1 in comparison to unionObject and add the missing fields with value of null; For instance object1:

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

And unionObject is:

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

So here object1 is missing files with fields http and https and type; so my desired output would be:

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

Please note this is NOT my deiredoutput:

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

What is the best/cleanest way to do it in Node.JS; is there any module on NPM to do it in a clean way?

Thanks

Upvotes: 1

Views: 362

Answers (1)

Alexis King
Alexis King

Reputation: 43842

Here's a simple solution. It uses lodash, but it's not strictly necessary. You could replace the _.isUndefined and _.isPlainObject with their plain JS equivalents.

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>

Upvotes: 1

Related Questions