JavaScript:针对不同情况压缩对象分配

JavaScript: Compressing object assignment for different cases

我正在尝试根据特定情况设置对象的属性。我认为可以压缩以下代码,我正在寻找解决它的最佳方法。

注意:我考虑过使用 switch 语句,但它产生的行数几乎相同。

let oNoificationData = {};
if (data.type === 'newUser') {
    oNotificationData = {
        title: `${data.user} is online!`,
        icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`,
        body: 'A new user has come online',
    };
} else if (data.type === 'logoff') {
    oNotificationData = {
        title: `${data.user} has logged out!`,
        icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`,
        body: 'A user has logged out'
    };
} else if (data.type === "newMsg") {
    oNotificationData = {
        title: `new message from ${data.user}`,
        icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`,
        body: 'You have a new message!'
    };
} else if (data.type === "closeRoom") {
    oNotificationData = {
        title: `${data.user} has left the chat`,
        icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`,
        body: 'Chat user has left'
    };
}

所以使用对象

var notifications = {
  newUser : {
    title: `${data.user} is online!`,
    icon:`https://www.gravatar.com/avatar/${sHash}?d=mm`,
    body: 'A new user has come online',
  },
  logoff : {
    title: `${data.user} has logged out!`,
    icon:`https://www.gravatar.com/avatar/${sHash}?d=mm`,
    body: 'A user has logged out'
  }
}

而且只是

var obj = notifications[data.type];