简体   繁体   中英

Javascript: filling undefind properties in object from a default object

I am trying to fill in undefined properties into an object using values from a default object.

I am basically looking to do something like underscores's "_.default" function.

Here is what I have:

     defaults: function(anyObject){

      var argArray = Array.prototype.slice.call(arguments,1);

       for(var key in argArray){
        if(anyObject[key] == null){
            anyObject[key] = argArray[key];
          } 
        } return anyObject; 
       }  

I call the function with the following passed:

defaults({extension : ".jpeg"}, {extension : ".gif", quality : "high"});

and I want it to return the following:

=> {extension : ".jpeg", quality : "high"}

any suggestions?

I'd try something like this:

defaults: function(defaults) {
    var args = Array.prototype.slice.call(arguments, 1);

    for (var i = 0; i < args.length; i++) {
        var arg = args[i];

        for (var key in arg) {
            if (!(key in defaults)) {
                defaults[key] = arg[key];
            }
        }
    }

    return defaults;
}

This will only add new keys to defaults .

Try like this:

defaults: function(obj, def) {
  Object.keys(def).forEach(function(key) {
    obj[key] = obj[key] || def[key]; 
  });
  return obj;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM