Let's say I have a JSON file like this.
[
{
"id" : 1,
"name" : "Test 1",
"author": "John Doe",
"author_url": "https://example.com/john-doe"
},
{
"id" : 2,
"name" : "Test 2",
"author": "Jane Smith",
"author_url": "https://example.com/jane-smith"
},
{
"id" : 3,
"name" : "Test 3",
"author": "Peter Parker",
"author_url": "https://example.com/parker"
},
{
"id" : 4,
"name" : "Test 4",
"author": "Bruce Wayn"
}
]
See the last data in the JSON does not have an "author_url" key-value pair. Till not everything seems OK right?
This is how I am inserting data on the page with an ajax call.
var req = new XMLHttpRequest();
req.open('GET', document.baseURI + '/test.json');
req.onload = function() {
var data = JSON.parse(req.responseText), index;
if (modal.innerHTML === '') {
// This can be ignored
// This is a snippet to find which data is to be inserted
for (var i = 0; i < data.length; i++) {
if (data[i].id == dataName) {
index = i;
}
}
// Here is the issue
var htmlData =
`<div class="modal">
<div class="modal-head">
<h2>` + data[index].name + `</h2>
</div>
<div class="modal-body">
<div class="content">
<div class="align-center">
<h3>` + data[index].name + `</h3>
</div>
<p class="mt-10 mb-10"><span style="color: black">Author : </span><a class="link-red" href="` + data[index].author_url + `">` + data[index].author + `</a></p>
</div>
</div>
</div>`;
modal.innerHTML = htmlData;
}
}
In the above code, you can see that data[index].author_url
is used to add the authors URL what if there does not exist any key with name author_url in the JSON file? Is there any way to add conditional logic to check if a key exists in the JSON file?
I am using vanilla javascript can this code be converted to ES6 or ES7?
EDIT: I not only want to check if the key exists or not but also want to load elements accordingly.