Ryan Ryan - 4 months ago 8
Javascript Question

Check if an any key/value does not exists in an object (with pure js)

So let's say this is my object:

var data = {
key1 : 'a',
key2 : 'b',
key3 : 'c'
};


And I have a function that loads my default settings like this:

function defaults() {
data.key1 = 'a';
data.key2 = 'b';
data.key3 = 'c';
data.key4 = 'd';
}


How can I check if any of the 'default' values are missing?

Answer

Since this is tagged jQuery the easiest would be use $.extend() to merge two objects

var data = {
  key1 : 'xxxxxxxx'  
}

var defaults = {
  key1 : 'a',
  key2 : 'b',
  key3 : 'c'
};

var results = $.extend(defaults,data);

console.log(results)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

In plain JS

  for( key in defaults){
    if (!data.hasOwnProperty(key) && defaults.hasOwnProperty(key)){
        data[key] = defaults[key];
    }
  }