John R Perry
John R Perry

Reputation: 4192

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?

Upvotes: 0

Views: 981

Answers (4)

charlietfl
charlietfl

Reputation: 171690

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];
    }
  }

Upvotes: 2

Jack jdeoel
Jack jdeoel

Reputation: 4584

object.hasOwnProperty can check the object key is exist.You have default function ,to access this data you need to do return.

var data = {
  key1 : 'a',
  key2 : 'b',
  key3 : 'c'
};
function defaults() {
  d = {};
  d.key1 = 'a';
  d.key2 = 'b';
  d.key3 = 'c';
  d.key4 = 'd';
  return d;
}
var object = defaults();
var miss = [];
for(var i in object){   
    if(!data.hasOwnProperty(i)){
        miss.push(i);
    }
}
console.log(miss);

Upvotes: 0

shinymoon
shinymoon

Reputation: 44

I tried the following. But someone already posted=)

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

function defaults() {
    for (var key in data_default) {
        if (!data.hasOwnProperty(key) || data[key] == "") {
            data[key] = data_default[key];
        }
    }
}

Upvotes: 0

Paul
Paul

Reputation: 36339

data.key1 = data.key1 || 'a';

Loads what's already there. If it's null or undefined or false in any way it loads 'a'

Upvotes: 0

Related Questions