Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have an object called defaultOptions and a function that accepts as an argument an object called newValues meant to override the values in defaultOptions with its own. The values that are not specified in newValues should remain default.

var configOptions = {
    isActive: false,
    name: "",
    description: "",
    category: "",
    group: "default"
}

    publishOptions: function(newValues){
      $.each(newValues, function(key, value){
        if(configOptions.hasOwnProperty(key)){
          configOptions[key] = value;
        }
        else{
          configOptions[key] = value;
        }
      });
      console.log(configOptions);
    }

For example, if I use this method like so:

var myOptions = {
    name: "option one",
    category: "the best"
}

publishOptions(myOptions)

I would expect configOptions to look like this:

configOptions = {
    isActive: false,
    name: "option one",
    description: "",
    category: "the best",
    group: "default"
}

I'm using jQuery's each method to map the values from newValues to configOptions, but I suspect there is a much more succinct and elegant way to do this. I would appreciate any suggestions.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

jQuery has extend, which seems to be what you are looking for:

http://api.jquery.com/jquery.extend/

Otherwise, if you don't want to use jQuery at all, you can make a for loop:

var first  = { value: 1, string: "two" };
var second = { value: 2 };

for ( var i in second )
  if ( first.hasOwnProperty( i ) )
    first[i] = second[i];

first.value == 2; // true



As a side, your if statement isn't doing anything because both cases assign the value to configOptions.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.