I’m displaying a series of objects. Sometimes, I will run into a situation where an object will be empty. How can I ensure the HTML markup doesn’t display on the page, when the object is empty?
var eventList = [
{
header: "Main Header One",
title: "This is Title One",
text: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellat enim laborum ullam officia sed deleniti libero tempora maxime nulla cum, modi labore ex repudiandae similique.",
link: "google",
linkText: "Google"
},
{
//no data in this object. I don't want the card to display at all if there's no data.
header: "",
title: "",
text: "",
link: "",
linkText: ""
},
{
header: "Main Header One",
title: "This is Title One",
text: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Repellat enim laborum ullam officia sed deleniti libero tempora maxime nulla cum, modi labore ex repudiandae similique.",
link: "yahoo",
linkText: "Yahoo"
}
];
//View
$.each(eventList, function(key, value) {
$('.list').append(
`<div class="card mb-3">` +
`<h5 class="card-header">` + value.header + `</h5>` +
`<div class="card-body">` +
`<h6 class="card-title">` + value.title + `</h6>` +
`<p class="card-text">` + value.text + `</p>` +
`</div>` +
`<div class="card-footer">` +
`<a href="https://` + value.link + `.com">` + value.linkText + `</a>` +
`</div>` +
`</div>`
);
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css"></script>
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="list"><div>
</div>
</div>
</div>
2
Answers
You can use jquery grep to filter the data and remove object which contains empty string, then you can use
$.each