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.
JavaScript
x
20
20
1
const welcomeMessages = {
2
english: "Welcome",
3
french: "Bienvenue",
4
italian: "Benvenuto",
5
spanish: "bienvenido",
6
russian: "Добро пожаловать",
7
chinese: "歡迎",
8
finnish: "Tervetuloa"
9
};
10
11
function addWelcomeMessage(language, message) {
12
// ** write your code here **
13
}
14
15
addWelcomeMessage("danés", "Velkommen");
16
addWelcomeMessage("zulú", "Ukwamukela");
17
18
console.log(welcomeMessages.danés); // "Velkommen"
19
console.log(welcomeMessages.zulú); // "Ukwamukela"
20
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:
JavaScript
1
14
14
1
const welcomeMessages = {
2
english: "Welcome",
3
french: "Bienvenue",
4
italian: "Benvenuto",
5
spanish: "bienvenido",
6
russian: "Добро пожаловать",
7
chinese: "歡迎",
8
finnish: "Tervetuloa"
9
};
10
11
function addWelcomeMessage(language, message) {
12
welcomeMessages[language] = message;
13
}
14
You could also add a small check to see if the message already exists, so that you don’t have duplicate entries.
JavaScript
1
14
14
1
const welcomeMessages = {
2
english: "Welcome",
3
french: "Bienvenue",
4
italian: "Benvenuto",
5
spanish: "bienvenido",
6
russian: "Добро пожаловать",
7
chinese: "歡迎",
8
finnish: "Tervetuloa"
9
};
10
11
function addWelcomeMessage(language, message) {
12
if(!welcomeMessages[language]) welcomeMessages[language] = message;
13
}
14
Another way is to use Object.assign()
function
JavaScript
1
14
14
1
const welcomeMessages = {
2
english: "Welcome",
3
french: "Bienvenue",
4
italian: "Benvenuto",
5
spanish: "bienvenido",
6
russian: "Добро пожаловать",
7
chinese: "歡迎",
8
finnish: "Tervetuloa"
9
};
10
11
function addWelcomeMessage(language, message) {
12
Object.assign(welcomeMessages, {language, message});
13
}
14
Though you don’t necessarily have to wrap them inside a function, you can just do this instead:
JavaScript
1
3
1
Object.assign(welcomeMessages, {"danés", "Velkommen"});
2
Object.assign(welcomeMessages, {"zulú", "Ukwamukela"});
3