What is the process of using an if statement in jQuery to verify the existence of a property in a JSON file?

I am working on a task to incorporate an if statement that checks for the existence of a specific property in a JSON file. If the property exists, I need to display its value within HTML tags <div class='titleHolder'> and

"<div class='posterHolder'>"
. I only want to include this property X between these two divs if it is present in the JSON file.

$(document).ready(function () {

    $.getJSON("js/appjson.json", function (data) {
        for (var i = 0; i < data.length; i++) {
            $('#jsonLoad').append('<a href="movies.html?id=' + data[i].id + '" + <div class="itemsHolder">' +
                "<div class='titleHolder'>" +
                "<h2 >" + data[i].name + "</h2>" +
                "</div>" +
                "<div class='posterHolder'>" + data[i].posterPath + "</div>" +
                "<div class='summaryShort'>" + data[i].summary + "</div>" +
                "<div class='raiting'><p>" + data[i].imdb + "</p></div><div class='genderMovie'> " + data[i].gender + "</div> " +
                "<div class='directorNdScreen'>" + 'Director by ' + " <p class='director'>" + data[i].director + '</p>' + '  ' + ' Screenplay by ' + "<p class='screenplay'>" + data[i].screenplay + "</p>" + "</div>"
     
                + "</a>")
        }
    })

});

Answer №1

Try breaking down your append section into separate variables and then combining them together. This approach might be helpful?

 $(document).ready(function() {
 $.getJSON( "js/appjson.json", function(data) {
 for (var i = 0; i < data.length; i++) {
       var content_append = "normal content";
        if(data[i])
        {
          content_append = "content here with data[i]"
        }

          $('#jsonLoad').append(content_append);
       }
     });

});

Answer №2

'<div>' + 
(condition === condition2)? 'data1' : 'data2' +
'</div>'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

If the text width of a label exceeds the total width of its container, intelligently display a sub-string based on pixel calculations

I am looking to shorten the text inside a label if its width exceeds the total width of its container. Instead of displaying the full text, I want to display a sub-string of it. if (SensorType.Text.Length >= 25) { SensorType.Text = SensorType.Text ...

Efficient Techniques for Deleting Rows in a Dynamic JavaScript Table

I'm facing an issue where I want to remove each line added by the user, one by one. However, my current program is removing all the rows from the table instead of just one at a time. The objective is to allow the user to remove a specific row if they ...

Preserve the div's aspect ratio using CSS styling

Is there a way to design a flexible div element that adjusts its width and height in sync with the window's size changes? Do any CSS techniques exist that would allow the height of the div to adapt based on the width, while still preserving its aspec ...

Changing JSON String into a File in Java

I need help converting an Object to JSON, and then converting it to a File in order to send it to AWS S3 for storage. What is the most efficient way to convert the String for this task? Any suggestions would be appreciated! Below is my code snippet: Str ...

Node.js - Hitting maximum call stack size limit despite using process.nextTick()

I am currently developing a module for creating "chainable" validation in Express.js: const validatePost = (req, res, next) => { validator.validate(req.body) .expect('name.first') .present('This parameter is required') ...

Is it possible to scroll the grid horizontally?

I have a grid that scrolls vertically, with columns adjusting their width automatically. .grid { display: grid; overflow-y: auto; grid-template-columns: repeat(auto-fit, minmax($min-column-width, 1fr)); } Now, I'm attempting to create a horizon ...

conceal menu upon click (gradually disappear)

This is a basic HTML/CSS menu. Currently, it is functioning properly for page redirection (href). However, I would like it to hide after being clicked on. I plan to call a function that will initiate an AJAX request upon clicking. Here is the code on JS ...

Navigating through a collection of objects

My array consists of objects, each having the following structure: var car = { make: "", model: "", price: "" } I am attempting to iterate through each object and check if a specific property is defined in this manner: for (i = 0; i <= ...

Navigate within a div using arrow keys to reposition another div

As a newcomer to JavaScript, I am facing some challenges. My goal is to use arrow keys to move a small div inside a larger div. However, the code below is not functioning as expected. Here is the HTML and CSS: <div id="rectangle"> <div id="s ...

What's causing the unexpected rendering outcome in Three.js?

Here is a mesh created in Blender: https://i.sstatic.net/KBGM5.jpg Upon loading it into Three.js, I am seeing this result: https://i.sstatic.net/PCNQ8.jpg I have exported it to .obj format and ensured all faces are triangulated. I am not sure why this is ...

Exploring the Magic of ES6 Object Destructuring

Learning about ES6 destructuring is still new to me. I have encountered a scenario where I need to extract specific values from a nested object within an object. For instance - z = {g: 1, h: 2, i: {d1:5, d2:6, d3:7}} When attempting to destructure with ...

Filling an HTML template with an $http response in VueJS

After learning about VueJs, I decided to embark on a small project - a nutrition app where food recommendations are made based on specific nutrients. Below is the JavaScript code snippet: recommendFood: function() { this.recs = {}; ...

How can I customize the list view and enable the OOTB Preview feature?

In my document library, I have successfully formatted the list view. While this has been effective, we are now missing out on the default functionality of SharePoint online where you can preview files within the main window with all the added benefits such ...

I'm only appending the final element to the JavaScript array

Currently, I have the following code: I'm endeavoring to create a new JSON object named dataJSON by utilizing properties from the GAJSON object. However, my issue arises when attempting to iterate over the GAJSOn object; only its last element is added ...

What is the best way to send an array from ajax to php?

I'm having an issue passing an array from AJAX to PHP (controller). What could be the issue with the second block of code given that var_dump($data) in the first block returns the expected content while in the second it returns NULL? FIRST. GOOD. f ...

How does AJAX relate to XML technology?

Well, let's clear up this misconception about XML and AJAX. The term "Asynchronous JavaScript And XML" may seem misleading because you can actually use an XMLHttpRequest object to fetch not just XML, but also plain text, JSON, scripts, and more. So w ...

When the resolution changes, the text shifts away from the bar in CSS

When I adjust the resolution of my display, the text on my top bar also changes. Can anyone help me fix this issue? In normal view: With changed resolution or smaller browser window: This is my HTML code: <body> <div class="top-panel"> ...

Utilizing jQuery's AJAX GET method with custom parameters to retrieve webpage content

Seeking assistance with using jQuery's get function to call a php script. The php script returns a variable containing the main content of my page, excluding the header/footer. The goal is to update the page content without a reload. Any insights on ...

Utilizing JavaScript's Facebook Connect feature on a Ruby on Rails website

My ruby-on-rails web application is in need of integrating "Facebook connect" functionality to enable users to share various activities on Facebook. Are there any Javascript methods I can use for this purpose? Any demos you can suggest? In addition, I wou ...

The widths of inputs vary between FireFox and Chrome

I've been investigating why the widths in FireFox and Chrome show a significant difference. This variation is causing a problem with my Modal in the views. Chrome: FireFox: Upon comparing the photos, it's clear that the width of the input in C ...