Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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"});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading