How to apply conditions in this string template?

Asked

Viewed 421 times

7

Currently I own this object:

const messages = {
  required: field => `${field} é obrigatório e naõ foi preenchido!`,
}

That prints the following value:

name é obrigatório e não foi preenchido!

I need to apply a condition to this string template that changes the field value based on a condition. I tried something like:

const messages = {
  required: field => `
   ${field => {
    if(field === 'name') {
     'nome'
    }
    if(field === 'address') {
      'endereço'
    } 
   }} é obrigatório e não foi preenchido
  `,
}

But when I print I get:

field => { if(field === 'name') { return 'nome' } } é obrigatório e não foi preenchido

And I need:

nome é obrigatório e não foi preenchido.
  • 1

    A question I always ask for people who are more recently and have already caught the time of CSS3+ and ES6, is it really necessary? In both CSS3 and ES6 I know there are a lot of things that look cool, but do we really need them? For example, the other day asked how to put a CSS drawing as bg below each TD, formulated an advanced and complex response, but a simple SVG image with background-image would solve and work even better ...

  • 1

    ... The same goes for template strings, do you really need to put logic inside the string? Wouldn’t it be better to set a var to each IF and then play in the template already handled? Do we need all this complexity? Why not the simplest and most intuitive? ... I honestly think that JS and CSS have created cool things, but not everything is actually useful, it actually seems to get in the way more.

  • 1

    Young man, putting expressions inside a template string makes it very difficult to read. Maybe we should rethink how to create this string.

  • @Guilhermenascimento thanks for the tips

2 answers

5


I was able to do it this way:

const fields = {
   address: 'Endereço',
   name: 'Nome'
}

const messages = {
  required: field => `${Object.keys(fields).includes(field) ? fields[field] : ''} é obrigatório e não foi preenchido`
}

console.log(messages.required('name'))
console.log(messages.required('address'))

I added a ternary condition inside the string template, it recognizes without problems, it is not possible to use if and else inside the string template.

In Object.keys(fields).includes(field) ? fields[field] I’m checking if there’s a key inside the object fields that matches the requested field, if any, it brings the value as a result.

As mentioned by @Guilherme Nascimento, it is preferable to put logic outside the string template to make it easier to read/maintain the code

const fields = {
   address: 'Endereço',
   name: 'Nome'
}

function getFieldText(field) {
  return Object.keys(fields).includes(field) ? fields[field] : ''
}

const messages = {
    required: field => `${getFieldText(field)} é obrigatório e não foi preenchido`
}

console.log(messages.required('name'))
console.log(messages.required('address'))

  • It works well, however I can have more than one condition to do, I will update my question to be clearer

  • 1

    Excellent resolution, was well organized in the end.

3

For the sake of organization and reading, it is preferable to avoid placing large expressions inside a string template.

The ideal would be to formulate the logic outside the string template and save the value in a variable, passing it in the string template interpolation.

const messages = {
    required: field => {

        let field_name = field;

        if (field === 'name') {
            field_name = 'nome';
        } else if(field === 'address') {
            field_name = 'endereço';
        }

        return  `${field_name} é obrigatório e não foi preenchido`
    },
}


console.log(messages.required('name'))
console.log(messages.required('address'))
console.log(messages.required('idade'))

That way, if you (or someone else) has to change the code, it will be easier to implement some new condition or logic.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.