kmoney12
kmoney12

Reputation: 4490

Overwrite/Merge two objects in JavaScript/jQuery

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?

Upvotes: 1

Views: 1796

Answers (2)

user229044
user229044

Reputation: 239541

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"}

Upvotes: 1

nnnnnn
nnnnnn

Reputation: 150080

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).

Upvotes: 6

Related Questions