Javascript:用另一个对象中的字段只覆盖一个对象的现有字段

Javascript: Overwrite ONLY existing fields in one object with the fields in another

本文关键字:字段 一个对象 覆盖 Javascript      更新时间:2023-09-26

javascript中有办法吗将一个对象中命名字段的值分配给另一个对象的相同字段(如果且仅当目标字段存在)。也就是说,覆盖旧值,不添加新值,使用表意结构、一行代码(特别适用于javascript和/或jQuery),并且决不循环,甚至适用于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"
... 
}

不保留字段1和字段3之后的旧字段。

jQuery.extend-可以覆盖值,但也可以复制新字段。

我们有哪些选择?

http://jsbin.com/owivat/1/edit(下划线)-我喜欢这个,现在是时候找到jquery的方法了。

结果:

_.extend(theTarget, _(theSource).pick(_(theTarget).keys()));

142850操作/秒

Object.keys(theTarget).map(function(a) { if (a in theSource) theTarget[a] = theSource[a]; });

403243操作/秒

这里有一行:)

for(var propertyName in theTarget)theTarget[propertyName]&&(theTarget[propertyName]=theSource[propertyName]);

使用underscore.js,您可以执行以下操作:

_(theTarget).extend(_(theSource).pick( _(theTarget).keys() ));

好!oneliner!没有可见的循环!

Object.keys(theTarget).map(function(a){ if(theSource[a]) theTarget[a]=theSource[a]})

虽然地图的来源有一个循环,但我确信。但我认为这是在没有可见循环结构的情况下实现它的唯一方法。尽管它滥用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版本中不起作用。

你可以手动完成,我不明白为什么"没有循环"。jQuery也以某种方式循环:

var result = {};
for (var key in theSource) {
  if (theTarget[key]) result[key] = theSource[key];
}

您必须遍历source的键,检查它们是否存在(而不是它们是否为truthy,因为这不会复制到0''falsenullundefinedNaN),并将该值复制到结果对象。因为您不想覆盖源或目标,所以不要修改它们。

jQuery.overwriteOnlyExisting = function (source, target) {
    var result = {}, key;
    for (key in target) {
        result[key] = key in source ? source[key] : target[key];
    }
    return result
};
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 clone