jQuery.extend an object, whether or not it exists yet?
javascript, jquery
Solution
var membership = $.extend({}, membership , {
level: "gold"
});
JSFiddle: http://jsfiddle.net/gJ9d4/
Problem
The Problem I am declaring certain properties of a parent object in undependable different places, such that it is difficult to predict whether the parent object will exist yet when I'm declaring these properties. No matter where this happens, I need the parent object to be created IF it doesn't exist yet, but not re-declared if it does. Example Say I have this JavaScript happening somewhere: ``` membership = { id: 5, name: "John" } ``` And at another point in the code (could be before the above code block or after), I have something like this: ``` membership.level = "gold"; ``` I essentially need to be able to have `membership.level` create the `membership` object if doesn't exist yet, but if it does exist, just add the `level` property. Similarly, the first code block needs to work in such a way that if `membership` exists already, it just adds the `id` and `name` properties. The Code I've Got So Far My solution did not work, but I think you'll be able to see what I'm going for. This is what I tried: 1st block ``` membership = $.extend(membership, { id: 5, name: "John" }); ``` 2nd block ``` membership = $.extend(membership , { level: "gold" }); ``` The above still errors sometimes, when membership is not defined. Is there a way to do this in the way I'm describing? Thanks in advance.