0

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.

Rajendran Nadar
  • 4,962
  • 3
  • 30
  • 51
  • 4
    It will say undefined so just check if data[index].author_url is not undefined – John Feb 20 '18 at 15:31
  • If this data comes from a request, it would be wise to use ES6 Promise. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – CodeTrooper Feb 20 '18 at 15:31
  • 1
    Use an inline ternary expression: data[index].name ? data[index].name : ''; – Ryan C Feb 20 '18 at 15:33
  • @RyanCarlisle let me give it a try! – Rajendran Nadar Feb 20 '18 at 15:33
  • Alternatively you could use the [logical OR (`||`)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators) – Serge K. Feb 20 '18 at 15:34
  • 1
    You'd probably not want any of the ` – James Feb 20 '18 at 15:34
  • @John please give me a small demo – Rajendran Nadar Feb 20 '18 at 15:34
  • 1
    The one 'dirty' thing around the ternary is that your page is still going to render that div and h3. To remove that, you'll need to add logic outside of that. If you don't care about that, then it should work. – Ryan C Feb 20 '18 at 15:34
  • `data` is an object, hence you want to check the existence of a key/property. There are hundreds of questions with the same problem here on SO. – Andreas Feb 20 '18 at 15:35
  • 1
    Possible duplicate of [Checking if a key exists in a JavaScript object?](https://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object) – Andreas Feb 20 '18 at 15:36

1 Answers1

1

If you don't want to render the parent tags, perform the following (cleaner IMHO to put the logic into a function):

`<div class="modal-body">`
  + addAuthor(data[index]) + 
`</div>`

function addAuthor(dataObject) {
  if (dataObject.author_url) {
    return
    `<div class="content">` +
      `<div class="align-center">` +
      `<h3>` + dataObject.name + `</h3>` +
      `</div>` +
      `<p class="mt-10 mb-10"><span style="color: black">Author : </span><a class="link-red" href="` + dataObject.author_url + `">` + dataObject.author + `</a></p>` +
    `</div>`;
  } else {
    return '';
  }
}

You can also include the modal-body in the function if you want to take that out as well. Just used the content in the example. HTH

Ryan C
  • 572
  • 5
  • 18
  • @RaajNadar Any luck? – Ryan C Feb 20 '18 at 18:49
  • Need some more help can you give any idea to store the data in returned data in var. This idea seems to work but I have many keys to check if that exists or not and than import them. – Rajendran Nadar Feb 21 '18 at 04:11
  • Just give me an basic idea to store returned data in var don't write the whole code just give a snippet, and then I will give you the green tick. – Rajendran Nadar Feb 21 '18 at 04:14