Can I declare variable in a more cleaner way

Viewed 70

Is there a way to keep my code clean

diagMsg = homu.message['await'].welCH.stat
diagMsg.color = toggle === true ? '#ffffff':'#2c2f33'
diagMsg.msg = diagMsg.msg.replace('{{stat}}', 'Disabled')
diagMsg.foot = diagMsg.foot.replace('{{prefix}}', homu.guildSettings.get(message.guild.id, 'prefix'))
        console.log(diagMsg)

I was wondering if I can do the same thing without declaring diagMsg over and over... just like this

diagMsg = homu.message['await'].welCH.stat
        .color = toggle === true ? '#ffffff':'#2c2f33'
        .msg = diagMsg.msg.replace('{{stat}}', 'Disabled')
        .foot = diagMsg.foot.replace('{{prefix}}', homu.guildSettings.get(message.guild.id, 'prefix'))
        console.log(diagMsg)
3 Answers

You can create a separate object with all the new properties to assign and then use Object.assign()

diagMsg = homu.message['await'].welCH.stat
Object.assign(diagMsg, {
   color: toggle === true ? '#ffffff':'#2c2f33',
   msg: diagMsg.msg.replace('{{stat}}', 'Disabled'),
   foot: diagMsg.foot.replace('{{prefix}}', homu.guildSettings.get(message.guild.id, 'prefix'))
})

Try object spread:

const diagMsg = {
  ...homu.message['await'].welCH.stat,
  color: toggle === true ? '#ffffff':'#2c2f33',
  msg: diagMsg.msg.replace('{{stat}}', 'Disabled'),
  foot: diagMsg.foot.replace(
    '{{prefix}}', 
    homu.guildSettings.get(message.guild.id, 'prefix')
  )
};

Why not put some declarations outside the object literal?

const initalMessage = homu.message['await'].welCH.stat;
const color = toggle === true ? '#ffffff':'#2c2f33';
const msg = initalMessage.msg.replace('{{stat}}', 'Disabled');
const foot = initalMessage.foot.replace('{{prefix}}', homu.guildSettings.get(message.guild.id, 'prefix'));

const diagMsg = {
  ...initalMessage, 
  color,
  msg,
  foot
};
Related