How to check if variables are filled with strings? and not show them when empty

Asked

Viewed 78 times

-1

In the final result object, I could have several items, sometimes these are not registered, so I would like to avoid showing empty tags on the screen. Example:

mostrador.innerHTML = filtrados.map(
        (obj) => `
        <h4>${obj.cidade}</h4>
        <p>${obj.empresa}</p>
        <p>${obj.representante}</p>
        <p>${obj.telefone}</p>
        <p>${obj.email}</p>
        <p>${obj.empresa2}</p>
        <p>${obj.representante2}</p>
        <p>${obj.telefone2}</p>
        <p>${obj.email2}</p>
    `,

In the case of company2, representant2, phone2 and Email2 are not filled in, how could I check this to show only tags with strings filled in?

  • Try it like this: ${obj.empresa2 || ''}

  • 1

    @dvd just can’t do that inside the element <p>, because it will still occupy the space on the screen, even empty.

3 answers

4

That?

var obj = { cidade : undefined, estado : "", cep : "123" };
if (obj.cidade === undefined) console.log("cidade não tem valor");
if (obj.empresa === undefined) console.log("estado não tem valor");
if (obj.representante === undefined) console.log("cep não tem valor");

You obviously need to set all the rules better. And instead of playing a message on the console you might want to do something specific, like return from the function.

Generalizing the action can simplify a bit (I now consider invalid void as well):

var obj = { cidade : "abc", estado : "", cep : "123" };
if (obj.cidade === undefined || obj.cidade === "" ||
    obj.empresa === undefined || obj.empresa === "" ||
    obj.representante === undefined || obj.representante === "") console.log("algum campo não tem valor");

Or you can make a more generic code yet and even put a function:

var obj = { cidade : undefined, estado : "", cep : "123" };
if (temCampoInvalido(obj)) console.log("algum campo não tem valor");
var obj = { cidade : "cidade", estado : "", cep : "123" };
if (temCampoInvalido(obj)) console.log("algum campo não tem valor");

function temCampoInvalido(obj) {
    for (var value of Object.values(obj)) if (value === undefined) return true;
    return false;
}

I put in the Github for future reference.

4

You can only check if the value is valid within a repeat loop:

const filtered = objects.map(obj => {
  let html = '';

  for (let attr in obj) {
     if (obj[attr]) {
        html += `<p>${obj[attr]}</p>`
     }
  }

  return html;
});

Thus, it will only concatenate the HTML code in the output if obj[attr] is valid. This condition, including, you can change as your need. Even, if the object receives new fields in the future, the logic does not need to be adapted. As it traverses all fields of the object, it will not matter how many are, nor which are.

See working:

// Lista de objetos da aplicação
const objects = [
  {
    empresa: 'Empresa 1',
    representante: 'Foo',
    telefone: '(00) 0000-0000',
    email: '[email protected]',
    empresa2: 'Empresa 1 - 2',
    representante2: null,
    telefone2: null,
    email2: null
  }, {
    empresa: 'Empresa 2',
    representante: 'Foo',
    telefone: '(00) 0000-0000',
    email: '[email protected]',
    empresa2: 'Empresa 2 - 2',
    representante2: null,
    telefone2: '(11) 1111-1111',
    email2: null
  }
];

// Filtra os atributos nulos e constrói o HTML de cada objeto
const filtered = objects.map(obj => {
  let html = '';
  
  for (let attr in obj) {
     if (obj[attr]) {
        html += `<p>${obj[attr]}</p>`
     }
  }
  
  return html;
});

// Exibe o HTML dos objetos na página
for (let obj of filtered) {
  document.body.innerHTML += obj;
}

  • 1

    +1 - this is the answer that scales better and is not dependent on writing the properties and conditions "by hand"

2


You can use the ternary operator that will return the tag and value if it is not null. If the value is null, shows nothing:

mostrador.innerHTML = filtrados.map(
        (obj) => `
        <h4>${obj.cidade}</h4>
        <p>${obj.empresa}</p>
        <p>${obj.representante}</p>
        <p>${obj.telefone}</p>
        <p>${obj.email}</p>
        ${obj.empresa2 ? '<p>'+obj.empresa2+'</p>' : ''}
        ${obj.representante2 ? '<p>'+obj.representante2+'</p>' : ''}
        ${obj.telefone2 ? '<p>'+obj.telefone2+'</p>' : ''}
        ${obj.email2 ? '<p>'+obj.email2+'</p>' : ''}
`)
  • all suggestions are valid and have enriched my knowledge, but this is the one that best meets my need in this specific case since I already have a huge array with hundreds of objects and what I needed was a solution that avoided having to edit hundreds of lines. Thank you all!

Browser other questions tagged

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