Add new object properties to lodash

I have two objects, and I want to add properties from object A to object B, and I'm trying to use extend , which does not work, do I need to use something else?

a = { name = "value" name2 = "value2" } b = { name3 = "value" name4 = "value2" } 

I want A to contain as

 a = { name = "value" name2 = "value2" name3 = "value" name4 = "value2" } 
+5
source share
3 answers

_.extend (now called _.assign ) is really how you do it:

 _.assign(a, b); 

Live example :

 var a = { name: "value", name2: "value2" }; var b = { name3: "value", name4: "value2" }; _.assign(a, b); document.body.insertAdjacentHTML( "beforeend", "Result:<pre>" + JSON.stringify(a, null, 2) + "</pre>" ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script> 
+13
source

First of all, your specific objects are incorrect. Objects should be written as name:value pairs, separated by a colon (and not an equal sign). In addition, you must use comma delimiters to delimit the properties of an object, for example:

 var person = { firstName: "Matthias", lastName: "Eckhart", eyeColor: "blue" }; 

To extend an object with various properties through lodash , you can use _.assign(object, [sources], [customizer], [thisArg]) :

 var a = { name: "value", name2: "value2" }; var b = { name3: "value", name4: "value2" }; _.assign(a, b); // extend console.log(a); 
 <script src="https://raw.githubusercontent.com/lodash/lodash/3.10.1/lodash.min.js"></script> 
+4
source

I believe that you want to use the lodash merge function, not extend . See: Lodash - the difference between .extend () /. Assign () and .merge ()

+3
source

All Articles