1

I want my user input to overwrite the defaults, but have the defaults fill in the blank if the data is not there. Like so:

var userInput={
    name:"Pat",
    color: "green"
}
var defaults={
    name:"Trevor",
    color: "blue",
    state: "washington"
}
var finalObject=mergeObjects(userInput,defaults);
//Should produce:
{
    name:"Pat",
    color: "green",
    state: "washington"
}

Is this kind of merging/overwriting possible with jQuery? I did see this question but it works with arrays and does not overwrite like I need it to.

Any ideas?

Community
  • 1
  • 1
kmoney12
  • 4,413
  • 5
  • 37
  • 59

2 Answers2

6

jQuery's $.extend() method will do the trick:

var finalObject = $.extend({}, defaults, userInput);

Note that $.extend() modifies the object passed as the first argument (and returns it), so you probably want to pass an empty object so that your defaults and userInput don't get changed. You can pass as many objects as you like and they'll all get merged into the first one in the order supplied (so defaults comes before userInput for your desired result).

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
1

You want jQuery.extend, which is explicitly for merging two or more objects (the order of arguments is reversed from your hypothetical mergeObjects method):

var finalObject = $.extend(defaults, userInput);

finalObject // Object {name: "Pat", color: "green", state: "washington"}
user229044
  • 232,980
  • 40
  • 330
  • 338
  • it's worth noting explicitly here that in this example, `defaults` gets modified. This could be a problem if you were doing this a number of times - your defaults wouldn't be the same as they were at the beginning. In that case, http://stackoverflow.com/a/18668971/467386 is probably what you want. – Tom Auger Jun 09 '15 at 15:56