当且仅当目标字段存在时,javascript中有没有一种方法可以将一个对象中的命名字段的值分配给另一个对象的相同字段。即覆盖旧值,不添加新值,使用表意结构,单行程序(专门用于javascript和/或jQuery),以及不以任何方式循环,甚至是for-in。
var theSource = {
field1: "TEXT",
field2: "VAL",
field3: "ZZ",
field4: "4",
field5: "5"
},
theTarget = {
field2: "0",
field3: "",
field4: null,
field5: undefined
};就像这样
var result = jQuery.overwriteOnlyExisting(theTarget, theSource);
result === {
field2: "VAL"
field3: "ZZ"
...
}不保留field1和field3之后的旧字段。
jQuery.extend -可以覆盖值,但也可以复制新字段。
我们有哪些选择?
http://jsbin.com/owivat/1/edit (下划线)-我喜欢这个,现在是时候找到jquery的方法了。
结果:
_.extend(theTarget, _(theSource).pick(_(theTarget).keys()));142,850次/秒
Object.keys(theTarget).map(function(a) { if (a in theSource) theTarget[a] = theSource[a]; });403,243次/秒
发布于 2013-06-27 17:40:07
var theSource = {
field1: "TEXT",
field2: "VAL",
field3: "ZZ",
field4: "4",
field5: "5"
},
theTarget = {
field2: "0",
field3: "",
field4: null,
field5: undefined
};
var overrideExistingProperties = function (theTarget, theSource){
for (var property in theSource)
if (theSource.hasOwnProperty(property) && theTarget.hasOwnProperty(property))
theTarget[property] = theSource[property];
};
overrideExistingProperties(theTarget, theSource);
result = theTarget; //if you don't want to clonehttps://stackoverflow.com/questions/17337926
复制相似问题