Click the link to find the JSON node that corresponds to the onclick event

After parsing JSON, the JS code below is returning a list of movie titles for me. Each movie title node contains additional attributes and values that are not currently being displayed. My goal is to have the other values in that specific node displayed when the user clicks on the movie title in the list. How can I achieve this? Thank you.

I have provided an example dataset. The JS is generating an HTML list of all the movie titles. Multiple nodes with the same movie title but different "location" values can be observed. I want users to click on a movie title and see all the different locations for that specific movie title displayed in the HTML.

To see the current functionality, here is a JSFiddle link: JSfiddle

JSON DATA:

    fl({
  "nodes" : [
{
  "node" : {
    "title" : "180",
    "ReleaseYear" : "2013",
    "Director" : "Jayendra",
    "Writer" : "Umarji Anuradha, Jayendra, Aarthi Sriram, & Suba ",
    "Address" : "\n \n \n 555 Market St. \n San Francisco, CA\n United States\n \n \n See map: Google Maps \n \n",
    "Actor 1" : "Siddarth",
    "Actor 2" : "Nithya Menon",
    "Actor 3" : "Priya Anand",
    "Latitude" : "37.789952",
    "Longitude" : "-122.400158"
  }
},
{
  "node" : {
    "title" : "180",
    "ReleaseYear" : "2013",
    "Director" : "Jayendra",
    "Writer" : "Umarji Anuradha, Jayendra, Aarthi Sriram, & Suba ",
    "Address" : "\n \n \n Epic Roasthouse (399 Embarcadero) \n San Francisco, CA\n United States\n \n \n See map: Google Maps \n \n",
    "Actor 1" : "Siddarth",
    "Actor 2" : "Nithya Menon",
    "Actor 3" : "Priya Anand",
    "Latitude" : "37.797677",
    "Longitude" : "-122.394339"
  }
},
{
  "node" : {
    "title" : "180",
    "ReleaseYear" : "2013",
    "Director" : "Jayendra",
    "Writer" : "Umarji Anuradha, Jayendra, Aarthi Sriram, & Suba ",
    "Address" : "\n \n \n Mason & California Streets (Nob Hill) \n San Francisco, CA\n United States\n \n \n See map: Google Maps \n \n",
    "Actor 1" : "Siddarth",
    "Actor 2" : "Nithya Menon",
    "Actor 3" : "Priya Anand",
    "Latitude" : "37.791556",
    "Longitude" : "-122.410766"
  }
}
  ]
})

JAVASCRIPT:

    var sort_by = function(field, reverse, primer){
    var key = function(x) {return primer ? primer(x[field]) : x[field]};
    return function(a,b) {
        var A = key(a), B = key(b);
        return ((A < B) ? -1 : (A > B) ? +1 : 0) * [-1,1][+!!reverse];
    }
}

$.ajax({
    type: 'GET',
    url: 'list',
    async: false,
    jsonpCallback: 'fl',
    contentType: 'application/json',
    dataType: 'jsonp',
    success: function(data) {
        var tmp = [];
        for(var i=0;i<data.nodes.length;i++) {
            tmp.push(data.nodes[i].node);
        }
        tmp.sort(sort_by('title', true));
        var div = document.createElement('div');
        $('#film').append(div);
        $(div).attr( 'data-role', 'collapsible' );
        var heading = tmp[0]['title'][0];
        var h3 = document.createElement('h3');
        h3.innerHTML = heading;
        $(div).append(h3);
        h3=null;
        var title = '';
        for(var i=0;i<tmp.length;i++) {
            if(tmp[i]['title'] != title){ title=tmp[i]['title'];
                if(tmp[i]['title'][0] !== heading){
                    heading = tmp[i]['title'][0];
                    var div = document.createElement('div');
                    $('#film').append(div);
                    $(div).attr( 'data-role', 'collapsible' );
                    var h3 = document.createElement('h3');
                    h3.innerHTML = heading; 
                    $(div).append(h3);
                    h3=null;
                    var p = document.createElement('p');
                    $(div).append(p);
                }
                var film = "<a>"+tmp[i]['title']+"</a> <br />";
                $(p).append(film);
                film=null;
                $("#film").collapsibleset("refresh");
            }
        }
    }
});

function fl(json){
     console.log(json);   
}

Answer №1

In my previous experience, I have approached this task by loading an array of objects from a JSON file into a single array called "objects," and then extracting data from it using the array indices. You can view an example of this in action on my JSFiddle, which demonstrates a simulated AJAX request populating an array with links displaying only titles through the use of functions like displayLinks() and showCast(movieId) for additional details upon click. Feel free to reach out if you have any queries or need further clarification.

Update 1: I have updated the initial JSFiddle with a new version available at this link. The revised approach merges entries based on their titles. Unlike the first iteration that simply assigned the fetched data to movies, this one incorporates an auxiliary array named movieTitles to store unique movie titles and process them through a loop mechanism. This loop traverses each element in data, verifying if its .title value already exists within the movieTitles array. If found, the corresponding entry is retrieved using its index in

movies</code, allowing the concatenation of additional properties as desired. For those not yet included (<code>movieIndex
equals -1), both the movie and its title are added to the respective arrays before continuing this check until all data elements are accounted for.
My demonstration purposely omits differentiating capitalizations (e.g., Batman vs. batman) to encourage learning through hands-on exploration rather than providing a fully completed solution outright.

If you require further assistance, please do not hesitate to ask.

Answer №2

To extract data from a JSON string, you can simply use the $.parseJSON method which will convert the string into a JavaScript object.

If the JSON string has the structure shown below:

movies: {
    drama: [{ //Array of movies
        movieId: {
            title: 'title',
            rating: '',
            duration: ''
        }]
    },
    terror: [{ //Array of movies
        movieId: {
            title: 'title',
            rating: '',
            duration: ''
        }
    }]
}

You can easily retrieve the relevant object in the click event handler.

$(movie).on('click', function(){
    movieId = this.id;
    //Access the movie information from the parsed JSON object
    movieObj = movies.drama.movieId;
    // Add information to the DOM element
    $('list').append(movieObj.{attributeId});
})
   

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

Issue encountered in Next.JS when attempting to validate for the presence of 'window == undefined': Hydration process failed due to inconsistencies between the initial UI and the server-rendered

I encountered an issue that says: Hydration failed because the initial UI does not match what was rendered on the server. My code involves getServerSideProps and includes a check within the page to determine if it is running in the browser (window==&apo ...

Reorganizing JSON data with ES6 techniques

I have a scenario where I need to update tire quantities in an array like this: tires: [{ name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct2", quanti ...

What is the best way to map elements when passing props as well?

In my code, I am using multiple text fields and I want to simplify the process by mapping them instead of duplicating the code. The challenge I'm facing is that these textfields also require elements from the constructor props. import React, { Compon ...

Why is this specific element showing as undefined in the form during editing, but appearing correctly in both the debugger and console.log?

I've encountered an error that keeps popping up: "Cannot read property 'textContent' of undefined at HTMLDocument". This error specifically occurs when dogName, dogBreed, and dogSex are set within the 'click' listener. It's st ...

In order to resolve this issue, I must eliminate any duplicate objects and then calculate the total sum using JavaScript

I have successfully removed the duplicates so far, but now I am stuck on how to sum the Total_Quantity. Is there a way to achieve this within the reduced method itself? Any help would be appreciated. Thank you. const test = [ { Item_Nam ...

Trigger filter application upon jqgrid completion of loading

Currently, I am utilizing jqgrid's client-side filter functionality: var opts = { ... loadonce: true, ... } var grid = jQuery("#Grid"); grid.jqGrid(opts) grid.jqGrid('navGrid','#mpager',{edit ...

There was an issue with searching on the YouTube API: com.google.api.client.googleapis.json.GoogleJsonResponseException occurred, showing a 403 Forbidden

I have been diligently following the steps outlined in this tutorial to develop my own Youtube application. I successfully created a Browser-Android API Key and implemented it into my project. However, upon attempting to run the application and conduct a s ...

Uncovering the secrets to fetching numerous JSON files asynchronously using JavaScript and JQuery

My goal is to fetch multiple JSON files using JavaScript or jQuery and extract elements named j_name, j_value, and j_sts into sarr[i], rarr[i], and parr[i], respectively. var sarr = new Object; var rarr = new Object; var parr = new Object; //num_json rep ...

What is the most effective way to transfer an array from one PHP file to a different JavaScript file?

Utilizing AJAX to send a request to another php page and retrieve the result of a query, I originally used xmlhttprequest to pass the php logic along with the query information. However, I wanted to separate the presentation logic from the actual code logi ...

Avoid using fs.read without returning a value to console.log

Seeking assistance with parsing a text file named information.txt and displaying the values using console.log. Here is the code snippet: fs.readFileSync("information.txt", "utf-8", function (err, data) { ...

What effect does setting AutoPostBack to "true" in an ASP dropdownlist have on the fireEvent() function?

I am currently working on an aspx page. This page includes three dropdown lists and a button, all of which are populated dynamically based on the code written in the code-behind file (.cs file). To achieve this, I need to utilize two event handler methods ...

Attempting to retrieve backend data through an API to be displayed on the frontend

After successfully sending form data from my React front end to the server using fetch, I am struggling to make this data accessible from the front end again. Despite being able to access and utilize the data within my API function on the server side, I&ap ...

Tips on extracting variables from JMeter Selenium WebDriver

Currently, I am dealing with a token that is being returned in the body of a web page. WDS.browser.findElement(org.openqa.selenium.By.xpath("//*[contains(@name,'RequestVerificationToken')]")).getText(); This token is what I need to extract: ...

Tips on incorporating the vue package

I recently started using Vue and decided to incorporate a plugin called vue-toastr. I'm attempting to integrate it with Laravel, which already has Vue set up with the plugin. Unfortunately, I keep encountering an error that says "TypeError: Cannot rea ...

Using Vue.js to bind data in two directions by using an object with v-for

I can't seem to get input data properly bound to object properties. When I try to iterate through an object to create input fields based on its attributes, the v-model data binding doesn't seem to be working as expected. Even with the code below, ...

Pictures failing to load on both Chrome and Safari browsers

For some reason, the images on my app are not appearing in Chrome and Safari but show up fine in Firefox. If you try to open the image URL in a browser, it works perfectly. However, when embedded in the HTML document, the image appears broken. I also test ...

The conversion of a map to a list is resulting in a null jolt output

I am looking to clean up the transformed JSON by removing any null values using a Jolt spec. Here is an example: Original JSON { "ratings": { "primary": 5, "quality": 4, "design": 5 } } Jolt specifi ...

Load the jQuery script only in the absence of cookies

Hey there! I have a cool fade out effect on a website I'm working on. When you go to the site, a div containing the title of the site appears and then fades away after a while. It's pretty simple yet effective. <div class="loader"><h1&g ...

Issue with breakpoints functionality in MUI v5 and React project

I've been attempting to utilize breakpoints for responsive design on my website, but unfortunately, it doesn't seem to be working correctly. Every time I implement a breakpoint, the entire page goes blank. Below is the code snippet I am working w ...

Restricting Jackson Serialization/Deserialization Depth for every class

I experimented with using the CustomJSONSerializer as suggested in this discussion on Stack Overflow. However, I encountered the following error: com.fasterxml.jackson.databind.JsonMappingException: object is not an instance of declaring class (through ...