Home > Software design >  Conditionally display data in HTML with conditions
Conditionally display data in HTML with conditions

Time:06-05

I want to print properties of an object like Nord, Est, Ouest... as elements in HTML like label: value which label is the name of direction and value its real value if exist! But sometimes some properties don't exist (i.e. they are null), so I want to render them only if they exist!

function print_directions(dirs) {
  let { nord, nordest, nordouest, est, sud, sudest, sudouest, ouest } =
    dirs;
  document.querySelector(".content").innerHTML = `
  <div d-none" : ""}">
    Nord:
    <span>${nord ?? ""}</span>
  </div>
  <div d-none" : ""}">
  nord-est:
    <span>${nordest ?? ""}</span>
  </div>
  <div d-none" : ""}">
  nord-ouest:
    <span>${nordouest ?? ""}</span>
  </div>
    <div d-none" : ""}">
      Est:
      <span>${est ?? ""}</span>
    </div>
    <div d-none" : ""}">
      Sud:
      <span>${sud ?? ""}</span>
    </div>
    <div d-none" : ""}">
      Sud-est:
      <span>${sudest ?? ""}</span>
    </div>
    <div d-none" : ""}">
      Sud-ouest:
      <span>${sudouest ?? ""}</span>
    </div>
    <div d-none" : ""}">
      Ouest:
      <span>${ouest ?? ""}</span>
    </div>`;
}
let dirs = { nord: 10, est: 19, sudouest: 5 };
print_directions(dirs);
.d-none {
  display: none;
}
<div ></div>

I've done this BUT it's too verbose? Any suggestion to make it short is much appreciated.

CodePudding user response:

you can do something like this

function print_directions(dirs) {
  const translations = {
    nord: 'Nord',
    sud: 'Sud',
    ouest: 'Ouest',
    est: 'Est',
    sudouest: 'Sud-ouest',
    sudest: 'Sud-est',
    nordouest: 'Nord-ouest',
    nordest: 'Nord-est'
  }

  const html = Object.entries(dirs).map(([dir, value]) => `<div >
    ${translations[dir] || dir}:
    <span>${value}</span>
  </div>`).join('') 
  document.querySelector(".content").innerHTML = html;
}
let dirs = { nord: 10, est: 19, sudouest: 5 };
print_directions(dirs);
.d-none {
  display: none;
}
<div ></div>

  • Related