Reputation: 1904
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
Reputation: 386883
I suggest to use a check first
location.receipt = location.receipt || {};
location.receipt.printRecipt = true;
Upvotes: 1
Reputation: 47961
You can do it in JavaScript in one statement:
var location2 = { recipt: { printRecipt: true } };
console.log(location2);
Upvotes: -2
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