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

时间:2017-12-08 00:31:23

标签: javascript object duplicates summarization

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

注意:我考虑过使用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'
    };
}

1 个答案:

答案 0 :(得分:1)

所以使用对象

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];