How to extend an object while ignoring null values?
javascript, jquery
Solution
You may use `undefined` as value which will be ignored by `jQuery.extend`.
var user = { "Name": "Dan",
"Age:" 27,
"Hobbies": undefined
};
$.extend(true, base, user);
Problem
Say for example I have an object of ``` var user = { "Name": "Dan", "Age": 27, "Hobbies": null }; ``` which I would like to merge onto the following base object so that my user object will have all the required properties ``` var base = { "Name": null, "Height": null, "Age": null, "Hobbies": [ { "Name": "Tennis", "Location": null }, { "Name": "Football", "Location": null }, { "Name": "Rugby", "Location": null } ] }; ``` The easiest way to merge to the two objects would be to extend the base object with the user object as follows ``` $.extend(true, base, user); ``` which would modify the base object to be ``` { "Name": "Dan", "Height": null, "Age": 27, "Hobbies": null }; ``` My question would be how can I get the extend method to not override null values? For example, in this instance, how can I still obtain a list of hobbies if the users hobby list is null so I end up with the following ``` { "Name": "Dan", "Height": null, "Age": 27, "Hobbies": [ { "Name": "Tennis", "Location": null }, { "Name": "Football", "Location": null }, { "Name": "Rugby", "Location": null } ] }; ```