Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 507
Max Avatar asked Jun 27 '13 08:06

Max


People also ask

How to copy properties from one object to another in JavaScript?

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.

How do you overwrite an object property?

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.

What's an object in JavaScript?

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.


1 Answers

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() ));
like image 136
David Fregoli Avatar answered Sep 19 '22 09:09

David Fregoli