javascript - Using underscore _.extend to avoid overwriting nested objects? -


var obj = {   customerinfo: {     fname: "tom",     lname: "smith",     age: 23,     height: 160   },   car: {     color: "red",     numwheels: 4   } }; 

i modify object into:

var obj = {   customerinfo: {     fname: "sally",     lname: "adams",     mname: "tully",     age: 23,     height: 160   },   car: {     color: "red",     numwheels: 4   } }; 

however, if do

_.extend(obj, {   customerinfo: {     fname: "sally",      lname: "adams",     mname: "tully"   } }); 

the object becomes

{   customerinfo: {     fname: "sally",     lname: "adams",     mname: "tully"   },   car: {     color: "red",     numwheels: 4   } }; 

and age , height have been wiped out.

what need preserve data that's nested?

and updating more complex objects?

http://jsfiddle.net/j4l18p7k/2/#share

there better ways of achieving deep merge behavior you're looking for...

you use jquery's $.extend api documented here: http://api.jquery.com/jquery.extend/

i've put little example match code sample since believe kind of generic approach merging you're looking for, right?

var o = {   customerinfo: {     fname: "tom",     lname: "smith",     age: 23,     height: 160,     paymentmethods: {       paypal: {         username: "sally"       }     }   },   car: {     color: "red",     numwheels: 4   } };  // wipes out more nested things (paypal disappears) var merge = $.extend(true, {} , o.customerinfo, {     "fname": "sally",     lname: "adams",     mname: "tully",     paymentmethods: {       visa: {         lastfour: "5555"       }     } });  console.dir(merge); 

http://jsfiddle.net/hrqbyd5c/9/

however pay attention jquery docs

on deep extend, object , array extended, object wrappers on primitive types such string, boolean, , number not. deep-extending cyclical data structure result in error.

for needs fall outside of behavior, write custom extend method instead, or use library lodash.

check out lodash's merge api documentation https://lodash.com/docs#merge

hope helped more...


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -