有条件地显示 HTML 中的数据

Conditionally display data in HTML with conditions

我想打印 Nord、Est、Ouest... 等对象的属性作为 HTML 中的元素,例如 label: value which label is the name of the direction and value its real value if exist! 但有时一些 属性 不存在(即它们是 null),所以我只想在它们存在时渲染它们!

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

我已经这样做了但是它太冗长了吗? 非常感谢任何使其简短的建议。

你可以这样做

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 class="info-dir">
    ${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 class="content"></div>