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

Transferring an array into jQuery UI Dialog

Currently, I am in the process of developing an ASP.NET MVC application that includes a postcode lookup feature. Once the user enters the postcode, it is sent to a web service which then returns an array of addresses. My goal is to present this array of ...

Tips for stopping ajax requests from automatically following redirects in jQuery

When utilizing the jQuery ajax functions to connect with a web service, I encounter an issue where the server redirects the response to a page with a 200 status code instead of providing a proper status code indicating an error. Unfortunately, I am unable ...

sorting through an array to extract values and seamlessly inserting them into a database with CodeIgniter

In the array provided, there is a nested array called studentAbsentId. I need to insert these values into the database. For example, if studentAbsentId 2 and studentAbsentId 3 are absent, I will need to insert two rows. Here is my updated code: print_r( ...

Error message: The Node.js filtered LS command is missing a ")" after the argument list

I've been working on the learnyounode workshop and I'm stuck on a code issue. After running it through jslint, I received this feedback: Expected ')' to match '(' from line 6 but instead saw '{'. Oddly enough, line ...

Sending JSON-encoded data using HTML5 Server-Sent Events (SSE) is a

I have a script that triggers an SSE event to fetch json encoded data from online.php. After some research, I discovered methods for sending JSON data via SSE by adding line breaks. My question is how to send JSON through SSE when the JSON array is genera ...

I am in search of a clean and efficient method to modify the class of a link that triggers an HTMX request in Django. Perhaps something like "auto-refresh" or a similar solution would be ideal

I've encountered an issue with HTMX in Django. The page consists of two main components: a list of categories and the content that is displayed when a category is clicked. Initially, everything was working smoothly with standard htmx functionality. H ...

Submitting Files to the API using Vue.js

I have the following code in Vue.js and I am trying to upload a file, but my issue is that I want to save the filename of the uploaded file to the JSON API using a POST method. Is there a way to achieve this? Thank you in advance. <div class="input-f ...

When using <body onload=foo()>, the function foo will not be executed

Having trouble with this code - it seems like initialize() is not being called. Check out the code here Any insight into why this might be happening? ...

Having trouble with the jQuery function not working as expected? Can't seem to identify any errors in the code?

I'm attempting to capture the essence of moving clouds from this beautiful theme: (I purchased it on themeforest, but it's originally designed for tumblr) Now, I want to incorporate it into my wordpress website here: The code used to be under ...

Ways to define css attributes for the "before" and "after" pseudo elements in the DOM

I'm looking to modify the color of the "border-left" property from its default red to a different color within the scope, such as blue. .hello:before { content:' '; display:inline-block; width: 22px; height: 25px; ...

Utilizing the split function within an ngIf statement in Angular

<div *ngIf="store[obj?.FundCode + obj?.PayWith].status == 'fail'">test</div> The method above is being utilized to combine two strings in order to map an array. It functions correctly, however, when attempting to incorporate the spli ...

Verifying the numerical value of a decimal place

How can I determine if the 4th decimal place in a number is zero or not? I want to throw an error message if it is not zero. For instance, in the number 2.3189, the value of the 4th decimal place is 9. My current code works for most cases, but for exampl ...

Gaining entry to information while an HTML form is being submitted

After a 15-year break, I am diving back into web development and currently learning Node.js and ExpressJS. I have set up a registration form on index.html and now want to transfer the entered data to response.html. However, when I hit Submit, the form is p ...

Moving an item to the top of an array in JavaScript/Vue.js: A simple guide

const a = [{ "iso2": "KH", "countryName": "Cambodia", "nationality": "Cambodian" }, { "iso2": "KI", "countryName": "Kiribati", "nationality": "I-Kiribati" }, { "iso2": "KM", "countryName": "Comoros", "nationality": "Como ...

encountering a problem with iterating through a JSON array

After making an ajax call and retrieving select options in json format, I implemented the code below to display these new options in place of the existing ones: success: function (data){ var $select = $('#dettaglio'); $select.html(' ...

execute the execCommand function following an ajax request

I am currently developing a WYSIWYG editor and encountering an issue with image handling using execCommand. Here is a simplified example of my page structure: <div id="buttons_panel"><input id="img_submit" type="button"/></div> <div ...

Using the goBack function in React Router does not add the previous location to the stack

In React Router v4, I have a list page and a details page in my web application. I want to implement a 'Save and close' button on the details page that redirects the user back to the list page when clicked. However, I noticed that after the user ...

Sliding an image from the left side to the right, and then repeating the movement from left to right

I am currently working on a CSS effect for some images. My goal is to have an image appear from the left side, move towards the right side, then reappear from the left and repeat this cycle. I managed to achieve this using the code below: @keyframes sli ...

Extracting information from Postgres and converting it to JSON format while dynamically updating the column names

Is there a way to selectively import specific columns from a table in json and alter their names during the process? For example: MyTable (id, column1, column2, columns3) I aim to transform them into json format as follows: MyTable: {column11, column2, ...

Trigger a child-mounted event and retrieve it from the parent component

Imagine I have a component named child. There is some data stored there that I need to retrieve in the parent component. To accomplish this, I plan to emit an event in the childs mount using this.$emit('get-data', this.data), and then receive it ...