Is there a way in javascript to assign values of named fields in an object to the same fields of another object, if and only if the target field exists. I.e. overwrite old values, NOT adding new values, using ideomatic constructs, one-liners (special for javascript and/or jQuery) and in no way loops, even for-in.
var theSource = {
field1: "TEXT",
field2: "VAL",
field3: "ZZ",
field4: "4",
field5: "5"
},
theTarget = {
field2: "0",
field3: "",
field4: null,
field5: undefined
};
Something like
var result = jQuery.overwriteOnlyExisting(theTarget, theSource);
result === {
field2: "VAL"
field3: "ZZ"
...
}
NO field1 AND old fields after field3 are preserved.
jQuery.extend
- can overwrite values, but it copies new fields as well.
Which options do we have here?
http://jsbin.com/owivat/1/edit (underscore) - I like this, now the time to find the jquery way.
Results:
_.extend(theTarget, _(theSource).pick(_(theTarget).keys()));
142,850 Ops/sec
Object.keys(theTarget).map(function(a) { if (a in theSource) theTarget[a] = theSource[a]; });
403,243 Ops/sec
Object.assign() The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
Using the spread operator to overwrite an object property We'll use the spread operator, which you can recognize by the three dots. Let's say we want the status to be true. We can use the following call. It's a super clean syntax and easy to see which value we are overwriting.
In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc. The same way, JavaScript objects can have properties, which define their characteristics.
here's the one-liner :)
for(var propertyName in theTarget)theTarget[propertyName]&&(theTarget[propertyName]=theSource[propertyName]);
with underscore.js
you can do:
_(theTarget).extend(_(theSource).pick( _(theTarget).keys() ));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With