Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend an object while ignoring null values?

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 }
    ]
};
like image 683
Dan Lister Avatar asked May 21 '12 14:05

Dan Lister


1 Answers

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);
like image 55
GodLesZ Avatar answered Sep 28 '22 04:09

GodLesZ