Skip to content
Advertisement

How to structure a function to add a key-value pair to a javascript object

Using javascript, how would you structure a function so that the rest of the code applies? which is to add a key/value pair to an existing JS Object.

const welcomeMessages = {
  english: "Welcome",
  french: "Bienvenue",
  italian: "Benvenuto",
  spanish: "bienvenido",
  russian: "Добро пожаловать",
  chinese: "歡迎",
  finnish: "Tervetuloa"
};

function addWelcomeMessage(language, message) {
  // ** write your code here **
}

addWelcomeMessage("danés", "Velkommen");
addWelcomeMessage("zulú", "Ukwamukela");

console.log(welcomeMessages.danés); // "Velkommen"
console.log(welcomeMessages.zulú); // "Ukwamukela"

I am aware that I can manually add the pair using

welcomeMessages.language = "message"

But am not sure how to create a function to simplify the process

Advertisement

Answer

Try:

const welcomeMessages = {
    english: "Welcome",
    french: "Bienvenue",
    italian: "Benvenuto",
    spanish: "bienvenido",
    russian: "Добро пожаловать",
    chinese: "歡迎",
    finnish: "Tervetuloa"
};

function addWelcomeMessage(language, message) {
    welcomeMessages[language] = message;
}

You could also add a small check to see if the message already exists, so that you don’t have duplicate entries.

const welcomeMessages = {
    english: "Welcome",
    french: "Bienvenue",
    italian: "Benvenuto",
    spanish: "bienvenido",
    russian: "Добро пожаловать",
    chinese: "歡迎",
    finnish: "Tervetuloa"
};

function addWelcomeMessage(language, message) {
    if(!welcomeMessages[language]) welcomeMessages[language] = message;
}

Another way is to use Object.assign() function

const welcomeMessages = {
    english: "Welcome",
    french: "Bienvenue",
    italian: "Benvenuto",
    spanish: "bienvenido",
    russian: "Добро пожаловать",
    chinese: "歡迎",
    finnish: "Tervetuloa"
};

function addWelcomeMessage(language, message) {
    Object.assign(welcomeMessages, {language, message});
}

Though you don’t necessarily have to wrap them inside a function, you can just do this instead:

Object.assign(welcomeMessages, {"danés", "Velkommen"});
Object.assign(welcomeMessages, {"zulú", "Ukwamukela"});
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement