Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from Object, with default value

I constantly find myself passing config values to functions accessing them like this:

var arg1 = 'test1'; if(isUndefined(config.args.arg1)){   arg1 = config.args.arg1; }   var arg2 = 'param2'; if(isUndefined(config.args.arg2)){   arg2 = config.args.arg2; }   var arg3 = '123'; if(isUndefined(config.args.arg3)){   arg3 = config.args.arg3; }  

where I later use them like this:

var url = '<some-url>?id='+arg1+'&='+arg2 +'=' + arg3; 

Does jQuery/ExtJS or any other framework provide a solution to access variables like this in a simple way, and give variables a default value?

Something like:

getValueOfObject(config,'args.arg3','<default>'); 

Or is there maybe a standard solution for this.

NOTE:

I was also thinking about the common pattern where you have defaults

var defaults = {    args: {       args1: ....    }    ... } 

and doing an object merge.

And then encoding the object to a param String. But as you can see the object values also sometimes contain parameter names.

like image 333
Jeremy S. Avatar asked Jan 25 '12 14:01

Jeremy S.


People also ask

How do you find the value of an object object?

Object. values() method is used to return an array whose elements are the enumerable property values found on the object. The ordering of the properties is the same as that given by the object manually is a loop is applied to the properties. Object.

What is the default value of object?

Variables of any "Object" type (which includes all the classes you will write) have a default value of null.

How do you assign default values to variables?

The OR Assignment (||=) Operator The logical OR assignment ( ||= ) operator assigns the new values only if the left operand is falsy. Below is an example of using ||= on a variable holding undefined . Next is an example of assigning a new value on a variable containing an empty string.

How do I find the first key value of an object?

Use object. keys(objectName) method to get access to all the keys of object. Now, we can use indexing like Object. keys(objectName)[0] to get the key of first element of object.


2 Answers

Generally, one can use the or operator to assign a default when some variable evaluates to falsy:

var foo = couldBeUndefined || "some default"; 

so:

var arg1 = config.args.arg1 || "test"; var arg2 = config.args.arg2 || "param2"; 

assuming that config.args is always defined, as your example code implies.

like image 156
karim79 Avatar answered Sep 27 '22 18:09

karim79


Looks like finally lodash has the _.get() function for this!

like image 36
Jeremy S. Avatar answered Sep 27 '22 20:09

Jeremy S.