当且仅当目标字段存在时,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 16:32:34
下面是一行代码:)
for(var propertyName in theTarget)theTarget[propertyName]&&(theTarget[propertyName]=theSource[propertyName]);使用underscore.js,您可以执行以下操作:
_(theTarget).extend(_(theSource).pick( _(theTarget).keys() ));发布于 2013-06-27 16:48:51
好的!眼线笔!没有可见的循环!
Object.keys(theTarget).map(function(a){ if(theSource[a]) theTarget[a]=theSource[a]})虽然map的源代码中有一个循环,但我敢肯定。但我认为这是在没有可见的循环构造的情况下实现它的唯一方法。尽管它滥用了javascript的全局命名空间,因此是肮脏的。
好吧,更好的是:
Object.keys(theTarget).map(function(a){ if(Object.keys(theSource).indexOf(a)) theTarget[a]=theSource[a]})更简洁
keys(theTarget).map(function(a){ if(a in theSource) theTarget[a]=theSource[a]}) 尽管keys()和Array#indexOf在旧的ecma版本中不起作用。
发布于 2013-06-27 16:15:42
你可以手动做,我不明白为什么“没有循环”。jQuery也以这样或那样的方式循环:
var result = {};
for (var key in theSource) {
if (theTarget[key]) result[key] = theSource[key];
}https://stackoverflow.com/questions/17337926
复制相似问题