Default values ​​for json in javascript

In code:

slider.init({ foo: "bar" }); var slider={ init:function(data){ } } 

If I use data.foo , I will get a "bar".

Suppose I have an optional variable called fish that can be included in a JSON variable. If I refer to data.fish , they will tell me that it is undefined, or an error or something like that will be thrown. Is there a way that I can assign a default value for the fish so that when I request data.fish , even if it is not set in the parameter, I will get the default value?

+4
source share
1 answer

You can use the operator or to assign default values ​​if they are not defined, for example:

 var slider = { init:function(data){ var fish = data.fish || "default value"; } } 

Or you can make the extend function to combine two objects similar to the jQuery extend function:

 function extend (obj1, obj2) { var result = obj1, val; for (val in obj2) { if (obj2.hasOwnProperty(val)) { result[val] = obj2[val]; } } return result; } var defaults = {val1: 1, val3: 3, fish: 'fish'}; extend(defaults, {val2: 2}); // returns Object val1=1 val3=3 fish=fish val2=2 
+8
source

All Articles