Search code examples
javascripthtmlecmascript-6ecmascript-2016

How to render propeties with nonzero values inside template strings


I am actually trying to render an HTMLElement using template strings. The function goes like this

function renderContent(){
  return `<div class="card">
              <span>Content goes here</span>
              <ul class="list">
                 ${renderList()}
              </ul>
          </div>`
}

And the renderList() function goes like this

function renderList() {
  const valueWithCount = { a : 1, b: 0, c:0, d:1}
  return Object.entries(valueWithCount).map(([key, value]) => {
    return `<li>
                    <span class="key">${key}:</span>
                    <span class="value">${value}</span>
            </li>`;
  });
}

I want the content to be rendered as

Content goes here
a:1
d:1

I dont want to render the the properties with value 0.I could write value && (some HTML content). But since its inside the template string, even 0 gets printed. If I go with ternary value ? some content : null , the behavior is same.The same case with undefined as well.

How do I avoid this?


Solution

  • Use .filter() instead of .map():

    function renderList() {
      const valueWithCount = { a : 1, b: 0, c:0, d:1}
      return Object.entries(valueWithCount).filter(([key, value]) => {
        if(value !== 0)
        return `<li>
                        <span class="key">${key}:</span>
                        <span class="value">${value}</span>
                </li>`;
       return null;
      });
    }
    

    return null in other cases.