How to get value from Object, with default value

前端 未结 4 810
梦毁少年i
梦毁少年i 2021-02-01 00:13

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

var arg1 = \'test1\';
if(isUndefined(config.args.arg1)){
  arg1 = config.ar         


        
相关标签:
4条回答
  • 2021-02-01 00:42

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

    0 讨论(0)
  • 2021-02-01 00:43

    With ES2018, you can now write options = { ...defaults, ...options }:

    Spread syntax - JavaScript | MDN

    Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().

    const obj1 = { foo: 'bar', x: 42 };
    const obj2 = { foo: 'baz', y: 13 };
    
    const clonedObj = { ...obj1 };
    // Object { foo: "bar", x: 42 }
    
    const mergedObj = { ...obj1, ...obj2 };
    // Object { foo: "baz", x: 42, y: 13 }
    
    0 讨论(0)
  • 2021-02-01 00:45

    try var options = extend(defaults, userOptions);

    This way you get all the userOptions and fall back to defaults when they don't pass any options.

    Note use any extend implementation you want.

    0 讨论(0)
  • 2021-02-01 01:00

    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.

    0 讨论(0)
提交回复
热议问题