Skip to content
Advertisement

How to spread an object as individual arguments in a function whose declaration I cannot change?

I have an object with some properties such as;

integrationConfig = {
  iconEmoji: ':myIconEmoji:', 
  team: 'myTeam', 
  text: 'myText', 
  channel: 'myChannel', 
  botName: 'myBot'
}

I am passing this object to a function below as shown (attachments is not important).

return await this.pushToSlack(...integrationConfig, attachments);

Importantly, this function is part of an NPM Package, so I don’t want to change the function declaration.

The function is declared like this:

exports.pushToSlack = function (channel, text, botName, iconEmoji, team, attachments, cb = function () {}) {
  // […]
}

I put some breakpoint to the pushToSlack function but the debugger didn’t jump into that line. I guess the function is not called somehow. I also receive this error:

Debug: internal, implementation, error 
    TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))
    at Function.all (<anonymous>)

Have you got any idea?

Advertisement

Answer

Spread syntax is not usable for that
use Destructuring assignment

integrationConfig = 
  { iconEmoji : ':myIconEmoji:'
  , team      : 'myTeam'
  , text      : 'myText'
  , channel   : 'myChannel'
  , botName   : 'myBot'
  } 

the call :

return await this.pushToSlack( integrationConfig, attachments);

the function :

 exports.pushToSlack = function ({channel, text, botName, iconEmoji, team}, attachments, ...
 //..Destructuring assignment....^.......................................^
 // Arguments can be in any order you want
 // and no obligation to have all of them
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement