1

我希望我的用户输入覆盖默认值,但如果数据不存在,则让默认值填写空白。像这样:

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

jQuery可以进行这种合并/覆盖吗?我确实看到了这个问题,但它适用于数组并且不会我需要的那样覆盖。

有任何想法吗?

4

2 回答 2

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

于 2013-09-07T02:07:41.310 回答
1

您想要jQuery.extend,它明确用于合并两个或多个对象(参数的顺序与您的假设mergeObjects方法相反):

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

finalObject // Object {name: "Pat", color: "green", state: "washington"}
于 2013-09-07T02:04:51.983 回答