Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Default Parameters in nested objects

I want to have a function with default parameters inside nested objects, and I want to be able to call it either f() or specifying only individual parameters.

// A function with nested objects with default parameters:

function f({ a = 1, callback = ({ name, param } = { name: "qwe", param: 123 }) } = {}) {
    console.log("a:", a);
    console.log("callback:", callback);
}

// And I want to run it like this:

f();
f({ callback: { params: "456" } });

// But 'callback.name' becomes undefined.
like image 244
TotalAMD Avatar asked May 10 '17 14:05

TotalAMD


3 Answers

When destructuring is mixed with default parameters, I admit the code is hard to read and write (especially when there are nested objects...).

But I think you are trying to do that:

function f({callback: {name = "cbFunction", params = "123"} = {}} = {}) {
  console.log(name);
  console.log(params);
}

f();
f({callback: {params: '789'}});
like image 105
Badacadabra Avatar answered Oct 06 '22 00:10

Badacadabra


I found none of the answers here to be what he wanted. But it IS actually possible in a somewhat sexy way by doing this:

(EDIT: Simplified syntax and also show how to add default values for subobjects)

function f({
    a = 1,
    callback = {}
  } = {}) {
  callback = { // default values
    name: "cbFunction",
    params: "123",
    ...callback // overwrites it with given values
  }
  // do the same for any subobjects
  callback.subObject = {
    arg1: 'hi',
    arg2: 'hello',
    ...callback.subObject
  }
  console.log("a:", a)
  console.log("callback:", callback)
}

f()
f({a: 2, callback: {params: '789', subObject: {arg2: 'goodbye'}}})
like image 28
Joakim L. Christiansen Avatar answered Oct 06 '22 00:10

Joakim L. Christiansen


Turned out to call it like this solves the problem, but is it the best way?

function f({
  a = 1,
  callback = ({
    name,
    param
  } = {
    name: "qwe",
    param: 123
  })
} = {}) {
  console.log("a:", a);
  console.log("callback:", callback);
}

f();
f({ callback: { name, params: "456" } });
like image 41
TotalAMD Avatar answered Oct 05 '22 23:10

TotalAMD