Search code examples
javascriptecmascript-6destructuring

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);
}

Solution

  • 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;
    }