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

Setting the error name in an extended Error class in Node.js: A step-by-step guide

My goal is to assign the error name as err.name = 'ExpressValidatorError'; within a custom Error class called class AppError extends Error that is then passed to centralErrorHandler for filtering and handling errors based on err.name. Despite ...

Playing around with Segment Analytics testing using Jest in TypeScript

I've been struggling to write a unit test that verifies if the .track method of Analytics is being called. Despite my efforts, the test keeps failing, even though invoking the function through http does trigger the call. I'm unsure if I've i ...

Cut out a passage by using a polyline shape

I am looking to create a unique effect by clipping a text like a heading1 using an svg polyline. The concept is to place the H1 text behind the polyline background and make it appear frosted or blurred. I have successfully achieved this in the past but see ...

AngularJS and numerous parallel indexed tables side by side

I need help with displaying two tables, one for profiles and the other for rates. The rates are connected to profiles through the rate name in the JSON data. Is there a way to show these two tables side by side? And when a row is selected in the profile ta ...

Tips for optimizing HTML5 markup elements to render effectively in Internet Explorer

How can I ensure that HTML5 markup elements such as <header>, <section>, and <footer> are displayed properly in Internet Explorer? I've noticed that when I apply CSS to these elements, the styling doesn't always work as expecte ...

Utilize C# and SmtpClient to efficiently send HTML emails

Is there a way to send HTML emails instead of plain text using SmtpClient? I have been following the code provided in this solution, but the output always ends up as plain text. For example, the link in the sample message below is not displayed as an activ ...

Conceal or reveal buttons using JavaScript

I am struggling with a function that is supposed to hide certain buttons and create a new button. When I click on the newly created button, it should make the previously hidden buttons visible again. However, the function does not seem to work properly. ...

Displaying a specific division solely on mobile devices with jQuery

I need to implement a feature where clicking on a phone number div triggers a call. However, I only want this div to be displayed on mobile devices. To achieve this, I initially set the div to "display:none" and tried using jQuery to show it on mobile devi ...

How can I modify the fill color of a Cell when hovering over a Bar Chart in Recharts?

I have been rendering the chart in the following manner: <BarChart width={868} height={40} data={data} margin={{top:0, bottom: 10, left:0, right:0}} barSize={5}> <Tooltip labelStyle={{ textAlign: &apo ...

Exploring the Vanilla JavaScript alternative to the jQuery.each() function

$.fn.slideUpTransition = function() { return this.each(function() { var $el = $(this); $el.css("max-height", "0"); $el.addClass("height-transition-hidden"); }); }; When utiliz ...

Experiencing difficulties with JavaScript/jQuery when encountering the 'use strict' error

I have been working on a small function to change the background of an HTML file, but I keep getting the 'Missing 'use strict' statement' error message from JSLint despite trying multiple solutions. Can anyone suggest how to resolve th ...

Varying levels of scaling on iPhone and iPad

I am currently working on a website project for my friend's brother and everything is running smoothly (for the most part). The layout of the site is designed with a centered container, leaving approximately 15-20% space from the left side. However, ...

json Exploring Input/Output Operations in SQL Server

When I insert serialized data into my SQL server, for example: "{\"Array\":\"Service\",\"Setting\":[{\"Id\":1},{\"Id\":2},{\"Id\":3},{\"Id\":4}]}" I then retrieve this value from the d ...

Utilize Java to launch the HTML file in a web browser

I have a specialized need for my HTML files to be displayed on a platform that is browser-free. The solution that immediately comes to mind for me in this scenario is utilizing applet. Therefore, I am interested in having my HTML file (including CSS and JS ...

When adding classes using Angular's ng-class, CSS3 transitions are not activated

After creating a custom modal directive in Angular, I am encountering an issue with the transition animation not working as expected. Within my directive's isolated scope, there is a method called toggleModal() that toggles the modalState between true ...

Last item in Material UI Grid container not filling up entire space

I designed a Grid container with 2 Grid columns, each containing 3 elements. However, I am facing an issue where the last element of each column is not appearing at the bottom as intended. What could be causing this problem? For reference, you can view th ...

Transform Vue.js into static HTML output

Is there a way to convert a Vue.js component into static html without the need for javascript? I am specifically interested in retaining styles. I am searching for a library where I can execute code similar to this: SomeNestedComponent.vue <template> ...

Learn how to display a tooltip for every individual point on a Highcharts network graph within an Angular

I am currently working on developing network graphs using highcharts and highcharts-angular within my Angular application. I have successfully managed to display the graph with datalabels, but now I need to implement tooltips for each point or node on the ...

Injecting controllers and classes dynamically using AngularJS

I'm currently working on a dynamic widgets list where each widget is defined by its html, class, controller, and name. Some of these parameters may be empty based on the type of widget. These widgets are then loaded dynamically into <li> element ...

Assigning a value using HTML code causes the input to malfunction

Trying to create a website with the goal of updating the database is proving to be challenging. The issue lies in the fact that some attributes from the database are in HTML format. Whenever I attempt to set an input's value to match the current attri ...