Deepak Bandi
Deepak Bandi

Reputation: 1904

Set the null value to a object

I'm working on a external API, where the default value of a object is null.

location.recipt = null;

But I need to set location.recipt.printRecipt to true, I created a fiddle and figured out unless I make location.recipt = {} I wont be able to set printRecipt, is there any other solution for this?

Because if that is the case I need to make 2 calls to the API, once to change from null to empty object {} and then again to update the data.

Fiddle : https://jsfiddle.net/bdeepakreddy/nwemtwtu/

Upvotes: 0

Views: 144

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386883

I suggest to use a check first

location.receipt = location.receipt || {};
location.receipt.printRecipt = true;

Upvotes: 1

GOTO 0
GOTO 0

Reputation: 47961

You can do it in JavaScript in one statement:

var location2 = { recipt: { printRecipt: true } };

console.log(location2);

Upvotes: -2

TheJim01
TheJim01

Reputation: 8896

No. null is null (nothing), and you can't set properties on nothing. Instead, you could make your default value be an object with a value property:

location.receipt = { value: null };

Upvotes: 0

LellisMoon
LellisMoon

Reputation: 5030

location.recipt={
    printRecipt : true
};

Upvotes: 2

Related Questions