Xun Yang
Xun Yang

Reputation: 4419

javascript: get un-destructed parameter in function

I need to get the un-destructed parameters inside a function. What would be the best way?

const foo = ({url, options, header, body, auth = 1}) => {
    //...do things with the parameters...
    let params = {url, options, header, body, auth}; // Is there an easy way?
    bar(params);
}

Upvotes: 0

Views: 101

Answers (1)

Danziger
Danziger

Reputation: 21161

You could have a single parameter in foo and do the destructuring inside it. Then, you would do some stuff with url, options, header, body and auth and finally call bar like bar({ ...args, auth }), spreading args and adding auth as well:

const bar = (baz) => {
  console.log(baz);
};

const foo = (args) => {
  const { url, options, header, body, auth = 1 } = args;

  // Do stuff with url, options, header, body and auth...

  bar({ ...args, auth });
};

foo({ url: 'www.google.com', options: {}, header: {}, body: 'Hi there!' });
foo({ url: 'www.google.com', options: {}, header: {}, body: 'Hi there!', auth: false });
.as-console-wrapper {
  max-height: 100vh !important;
}

Upvotes: 1

Related Questions