Problem
I declare some properties of the parent in independent locations, so it is difficult to predict whether the parent will still exist when I declare these properties. No matter where this happens, I need a parent object that will be created if it does not already exist, but will not be re-declared if it does.
Example
Say I have this JavaScript somewhere:
membership = {
id: 5,
name: "John"
}
And at another point in the code (maybe before the above code block or after) I have something like this:
membership.level = "gold";
I essentially need to have membership.levelan object created membershipif it does not already exist, but if it exists, just add a property level. Similarly, the first block of code should work in such a way that if it membershipalready exists, it simply adds the idand properties name.
The code I received so far
My solution did not work, but I think you can see what I'm going for. This is what I tried:
1st block
membership = $.extend(membership, {
id: 5,
name: "John"
});
Second block
membership = $.extend(membership , {
level: "gold"
});
The above errors sometimes occur when membership is undefined. Is there a way to do this the way I describe? Thanks in advance.
source
share