I am actually trying to render an HTMLElement using template strings. The function goes like this
function renderContent(){
return `<div >
<span>Content goes here</span>
<ul >
${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 >${key}:</span>
<span >${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?
CodePudding user response:
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 >${key}:</span>
<span >${value}</span>
</li>`;
return null;
});
}
return null in other cases.
