Transforming nested JSON files into nested jQuery divs

Is it possible to iterate through two JSON files that have a parent-child relationship based on simple ID primary and foreign keys? Can we then display the data in a list of divs with the following characteristics:

  1. Hierarchical - child divs should only appear under their respective parent divs, creating a structure like parent-child-child or parent-child-child-child.
  2. Expandable - child divs are initially hidden (display:none) but can be revealed by clicking on the parent div using jQuery's $(panelID).slideToggle(speed) method.
  3. Togglable with a separate checkbox - if the last key-value pair in either the parent or child div contains a key of "DEPRECATED", they should be able to be toggled.
  4. Sortable - Just kidding!

I rely on jQuery for functions such as parseJSON and cool display features, even though my JavaScript debugging skills leave much to be desired.

Edit: Below are the contents of the two JSON files being referenced:

types.json:

{"objtype":[{"NAME":"Animal","ID":"15","DEPRECATED":""},{"NAME":"Vegetable","ID":"8"},{"NAME":"Mineral","ID":"2","DEPRECATED":""}]}

objs.json:

{"objinstance":[{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"8","OBJNAME":"Fruit salad consisting of oranges and mangoes","OBJID":"454","DATEEXPIRES":"2014-09-01 00:00:00.0","DEPRECATED":""},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"8","OBJNAME":"Spicy V-8 juice","OBJID":"499","DATEEXPIRES":"2015-01-02 00:00:00.0"},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"2","OBJNAME":"Rental agreement for new apartment","OBJID":"2885","DATEEXPIRES":"2015-08-25 00:00:00.0"},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"2","OBJNAME":"Salt","OBJID":"1033","DATEEXPIRES":"","DEPRECATED":""},{"DATEBOUGHT":"","OBJTYPEID":"15","OBJNAME":"Koko the Monkey","OBJID":"68","DATEEXPIRES":"","DEPRECATED":""},{"DATEBOUGHT":"","OBJTYPEID":"15","OBJNAME":"Bubbles the Clown","OBJID":"69","DATEEXPIRES":"","DEPRECATED":""}]}

Answer №1

Consider this straightforward demonstration of how HTML markup can be dynamically generated using JSON data.

Approach:

  1. Parse the JSON string into JavaScript objects
  2. Iterate through the parent data
  3. For each parent data, create a parent div and populate it with the necessary content
  4. Go through the child data and look for matching id
  5. For every child data that matches the parent id, create a child div, insert the required content, and then append it to the parent div
  6. Attach the parent div to a container or the body
  7. Repeat the process as needed
  8. Customize CSS styles according to your preferences

.

Live Example: http://jsfiddle.net/abhitalks/h3nbwc1f/

Code Snippet:

var typesString = '{"objtype":[{"NAME":"Animal","ID":"15","DEPRECATED":""},{"NAME":"Vegetable","ID":"8"},{"NAME":"Mineral","ID":"2","DEPRECATED":""}]}';
var objsString = '{"objinstance":[{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"8","OBJNAME":"Fruit salad consisting of oranges and mangoes","OBJID":"454","DATEEXPIRES":"2014-09-01 00:00:00.0","DEPRECATED":""},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"8","OBJNAME":"Spicy V-8 juice","OBJID":"499","DATEEXPIRES":"2015-01-02 00:00:00.0"},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"2","OBJNAME":"Rental agreement for new apartment","OBJID":"2885","DATEEXPIRES":"2015-08-25 00:00:00.0"},{"DATEBOUGHT":"2014-08-26 00:00:00.0","OBJTYPEID":"2","OBJNAME":"Salt","OBJID":"1033","DATEEXPIRES":"","DEPRECATED":""},{"DATEBOUGHT":"","OBJTYPEID":"15","OBJNAME":"Koko the Monkey","OBJID":"68","DATEEXPIRES":"","DEPRECATED":""},{"DATEBOUGHT":"","OBJTYPEID":"15","OBJNAME":"Bubbles the Clown","OBJID":"69","DATEEXPIRES":"","DEPRECATED":""}]}';

var types = JSON.parse(typesString);
var objs = JSON.parse(objsString);

types.objtype.forEach(function(item, idx) {
    var $parent = $("<div class='parent' />");
    var $label = $("<label>").text(item.ID + ': ' + item.NAME).attr('for', 'c' + idx);
var $input = $('<input type="checkbox">').attr('id', 'c' + idx);
$parent.append($label);
    $parent.append($input);
    objs.objinstance.forEach(function(item2) {
        if (item2.OBJTYPEID == item.ID) {
            var $child = $("<div class='child' />");
            var txt2 = item2.OBJID + ': ' + item2.OBJNAME;
            $child.text(txt2);
            $parent.append($child);
        }
    });
    $("#wrap").append($parent);
});
div#wrap {
    font-family: helvetica, sans-serif;
    font-size: 17px;
}
div.parent {
    border: 1px solid blue;
    padding: 8px; margin: 4px;
}
div.child {
    border: 1px solid green;
    font-size: 15px;
    padding: 0px; margin: 0px;
    opacity: 0; height: 0px;
    transition: all 250ms;
}
label {
    cursor: pointer;
}
input[type=checkbox] {
    display: none;
}
input[type=checkbox]:checked  ~ div.child {
    padding: 8px; margin: 8px;
    opacity: 1; height: auto;    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap"></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

Modifying Checkbox BorderWidth in Material UI v5

Seeking assistance with adjusting the checkbox border width in Material UI v5. I currently have a custom checkbox and would like to remove the border width. Despite trying numerous solutions, I have been unsuccessful so far. checkbox <Checkbox de ...

Encountering an issue with React where the useContext hook is returning undefined instead of

I am facing an issue where I am attempting to access state and setState from the Store file, but it returns as undefined. Can someone help me understand what is causing this problem and how I can resolve it? import React, {createContext, useState} from &ap ...

Setting up Google Analytics Site Search without Query Parameters in the URL using JQUERY

I recently encountered an issue with the search function on my ASPX eCommerce site. Instead of using a query parameter like most search features, it renders searches using a path. For example, if you search for "Pants", the URL becomes /Search/Pants.aspx. ...

Using Javascript to retrieve information from a json file

I am currently working on incorporating JSON data into my script. I have noticed that when I manually declare a variable and check the console output, everything seems to work fine. <script> data = '[{"id": 1,"name": "Germany"},{"id": 2,"name": ...

The Django/Python function, toDataURL, outputs a response containing the string retrieved from the toDataURL method

I recently stored a string in a database that was returned by a javascript method called toDataURL. An example of the string can be found here: http://pastebin.com/0Qu8rngD My goal is to retrieve the image in a Django response. I've attempted various ...

What could be the reason behind receiving a TypeError upon refreshing the page, where it claims that a state is not found even though that may not be the actual situation?

Within my application, I have a component called Wall. Users are redirected to the Wall component after successfully logging in from the Login component. In the Wall component, I am retrieving and displaying the user's name that they used during regis ...

Using a div in React to create a vertical gap between two React elements

I am working with two React Components in my project - the Right Column and the Left Column. I am trying to create space between them using a div tag. Currently, my setup in the App.js file looks like this: import React from 'react'; import LeftC ...

JQuery method for altering currentTime's format

I am attempting to showcase the current time and duration of my videos on my website using the format 00:00, but I am having some difficulty... myVideo.on('timeupdate', function() { $('.current').text(myVideo[0].currentTime); $ ...

Exploring Object Arrays with Underscore.js

Here is an array of objects that I am working with: var items = [ { id: 1, name: "Item 1", categories: [ { id: 1, name: "Item 1 - Category 1" }, { ...

Executing a Function Following the Completion of getAuth() in React Firebase

I have a function that needs the user id to run properly. However, the function is executing before the getAuth process is completed. const user = getAuth() getDoc(doc(db, 'users', user.currentUser.uid)) When I try to run the above code, it thro ...

Adjust the size at the location of the cursor

I am having trouble understanding how to implement zoom based on mouse position using this example here: (https://stackblitz.com/edit/js-fxnmkm?file=index.js) let node, scale = 1, posX = 0, posY = 0, node = document.querySelector('.f ...

Is there a way to align the line under the hyperlinks to match the text size using CSS?

<div className={styles.container}> <ul className={styles.links}> <li className={styles.link}> <a href="/">Home</a> </li> <li className={styles.link}> <a href="/portfolio& ...

After updating the INNERHTML, the NAV tag content is no longer functional

I am facing an issue with replacing the contents of a NAV tag that contains UL list items. The original HTML within the NAV tag works perfectly fine, but when I replace it with my own HTML - which matches the original word for word - the dropdown functiona ...

Verify if the contract address corresponds to a token and retrieve the token details, such as its symbol

Can I use web3 to retrieve token information such as symbol and total supply similar to the etherscan API pro endpoint tokeninformation by providing the contract address? I'm interested in determining whether the addresses I collect are tokens or reg ...

Is there a bug hiding in the Angular code for the Codecademy Calendar App waiting to be found?

Currently, I am working on the Codecademy task - CalendarApp utilizing AngularJS which involves services and routing. Unfortunately, it seems to have some issues as the data is not displaying correctly and the expression: {{ day.date | date }} appears as i ...

Display or conceal DIVs with multiple attribute values according to the selected value in a dropdown menu using the jQuery Filter Method

I am attempting to display or hide multiple services, each with a custom attribute called data-serviceregion, which may have multiple values based on the selected option from the dropdown. <form class="book-now"> <select name="region" id="region" ...

AngularJS: Triggering events in one controller to update data in another controller

I've tried several examples, but I'm not getting the expected results. In my project, I have two controllers - one for a dropdown and one for a table. When a user selects an item from the dropdown, a factory triggers a get request to update the t ...

D3 and dimple line graphs

As I continue to explore D3, I am working on a project where I need to display data using the Dimple module for charting. The user should also have the ability to add parameters. I have experimented with two different ways of formatting my data, and I hav ...

What is the best way to transition an absolute positioned element from right to center?

When hovering over an overlay element, I want the <h3> tag to appear with a transition effect from right to center, similar to the example shown here. Could someone please assist me in achieving this? Thank you in advance. HTML <div class="row m ...

Retrieve the highest date value from a collection of objects

Within a React.js component, I have the following array: const data = [{ date: '2017-12-21T07:43:00Z', value: 7000 }, { date: '2017-12-21T09:41:00Z', value: 1500, }, { date: '2017-12-23T10:59:00Z', value: 2000 }] ...