JQuery.extend object, exists or not?

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.

+4
source share
3 answers
var membership = $.extend({}, membership , {
    level: "gold"
});

JSFiddle: http://jsfiddle.net/gJ9d4/

+5
source

:

membership = $.extend(membership || {} , {
    level: "gold"
});

undefined, .

Fiddle

0

jsFiddle Demo

||

var membership = membership || { id: 5, name: "John" };

Basically, if membership- undefined, then membership is set equal to the definition of the object, but if membershipdefined, then it is simply reassigned.

If you want, you can do this with an extended call.

//this could be used as the extend membership
var membership = membership || { id: 5, name: "John" };
membership = $.extend(membership , {
 level: "gold"
});//this could also be membership.level = "gold";
0
source

Source: https://habr.com/ru/post/1524172/


All Articles