By Mike K


2020-02-14 08:44:13 8 Comments

Is it possible to somehow pass arguments to an object?

Something like,

const messages = (str1, str2){
    1: `${str1} is not the same as ${str2}`,
    2: 'message2',
    3: 'message3',
    4: 'message4',
    5: 'message5',
    6: 'message6',
}

const validateInput = ({ str1 = '', str2 = '' }) => {
    if (str1 !== str2) {
        console.log(messages[1](str1, str2))
    }
}

validateInput('a', 'b')

I'm not looking for something like,

const message = (str1, str2) => `${str1} is not the same as ${str2}`

I'm curious to know if this can be done specifically with an object.

1 comments

@Nina Scholz 2020-02-14 08:49:40

You could take an object for all messages and inside function which return a string with a message, depending on the handed over strings.

const messages = {
    1: (str1, str2) => `${str1} is not the same as ${str2}`,
    2: (str1, str2) => 'message2',
    3: (str1, str2) => 'message3',
    4: (str1, str2) => 'message4',
    5: (str1, str2) => 'message5',
    6: (str1, str2) => 'message6',
};

const validateInput = (str1 = '', str2 = '') => {
    if (str1 !== str2) {
        console.log(messages[1](str1, str2))
    }
}

validateInput('a', 'b');

If you switch the order of calling messages with parameters first and then by a number, then only a single function is necessary.

const messages = (str1, str2) => ({
    1: `${str1} is not the same as ${str2}`,
    2: 'message2',
    3: 'message3',
    4: 'message4',
    5: 'message5',
    6: 'message6',
});

const validateInput = (str1 = '', str2 = '') => {
    if (str1 !== str2) {
        console.log(messages(str1, str2)[1])
    }
}

validateInput('a', 'b');

Related Questions

Sponsored Content

45 Answered Questions

[SOLVED] Sort array of objects by string property value

50 Answered Questions

[SOLVED] How do I test for an empty JavaScript object?

62 Answered Questions

[SOLVED] How to replace all occurrences of a string?

4 Answered Questions

86 Answered Questions

[SOLVED] How do I make the first letter of a string uppercase in JavaScript?

43 Answered Questions

[SOLVED] Detecting an undefined object property

21 Answered Questions

[SOLVED] Checking if a key exists in a JavaScript object?

42 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

67 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

63 Answered Questions

[SOLVED] How can I merge properties of two JavaScript objects dynamically?

Sponsored Content