Insert a new button option within a specific container for every array included in a JSON structure, and introduce additional buttons within the array options for each object contained within the arrays

I am struggling to generate buttons for each JSON array within the given JSON object. There are 2 arrays, and I aim to add child buttons to these initial buttons for every object in the arrays (a total of 6 objects). Even though I have written some code that I believe should work, it only results in an error. Below is the JavaScript code I have used. I've been working on this for a few days now and time is running out, so any guidance or advice would be greatly appreciated.

<body>
<div id="title"> <!-output how many modules there are with .length-->
</div>
<div id="nav">
</div>


<script>
    $( document ).ready(function() { 
        $.getJSON( "courses.json", function( json ) {
            for (var i in Object.keys(json)) {
                var btn = document.createElement("BUTTON");
                document.getElementById("nav").appendChild(btn);
                btn.id = "myBtn";
                    $.each(i, (function(j) {
                        var btns = document.createElement("BUTTON");
                        document.getElementById("myBtn").appendChild(btns);
                        }))
                    }
            })
    })

</script>
</body>

//JSON:

{
"semester1": [
        {"code":"CS6100", 
        "title":"Multimedia Authoring", 
        "Credit Weighting":5, 
        "Content":"Programming in Processing", 
        "Assessment":{"CA":40,"exam":60}, 
        "link":"https://www.ucc.ie/admin/registrar/modules/?mod=CS6100"},

        {"code":"CS6101",  
        "title":"Web Development for Digital Media", 
        "Credit Weighting":5, 
        "Content":"Web Development with programming in Client and Server Side Languages", 
        "Assessment":{"CA":40,"exam":60}, 
        "link":"https://www.ucc.ie/admin/registrar/modules/?mod=CS6101"},

        {"code":"CS6102", 
        "title":"Graphics for Interactive Media", 
        "Credit Weighting":5, 
        "Content":"Programming in Python. The principles, practices, technologies and critical frameworks associated with the practice of graphic design for digital media. Develop understanding of the creative and technical aspects of image capture, editing and manipulation. Production of graphics for digital media using industry-standard tools.", 
        "Assessment":{"CA":40,"exam":60}, 
        "link":"https://www.ucc.ie/admin/registrar/modules/?mod=CS6102"},

        {"code":"CS6103", 
        "title":"Audio and Sound Engineering", 
        "Credit Weighting":5, 
        "Content":"Introduction to the technologies and techniques used in digital audio. Physics of sound and the psycho-physiological basis of hearing. Sound engineering, production and post-production.", 
        "Assessment":{"CA":40,"exam":60}, 
        "link":"https://www.ucc.ie/admin/registrar/modules/?mod=CS6103"},

        {"code":"CS6104", 
        "title":"Digital Video Capture and Packaging", 
        "Credit Weighting":5, 
        "Content":"Develop understanding of the planning, production and post-production of digital video. Application and evaluation of industry-standard tools in capturing, processing and packaging digital video.", 
        "Assessment":{"CA":40,"exam":60}, 
        "link":"https://www.ucc.ie/admin/registrar/modules/?mod=CS6104"},

        {"code":"CS6111", 
        "title":"3D Graphics and Modelling", 
        "Credit Weighting":5, 
        "Content":"Tools, techniques and processes involved in 3D graphics design, modelling and rendering. Create appropriate models of 3D objects and scenes. Solving problems in curve, surface and solid modeling.", 
        "Assessment":{"CA":40,"exam":60}, 
        "link":"https://www.ucc.ie/admin/registrar/modules/?mod=CS6111"}
        ],

Answer №1

for (var i in Object.keys(json))

Iterating over each i in Object.keys(json), which generates an array of keys within an object (in the form of strings). When using $.each, it requires an array or object, but you are passing the index i, which is a string (e.g. "semester1").

You have two potential solutions: either pass json[i] to $.each instead of just passing i, like this:

...
    $( document ).ready(function() { 
        $.getJSON( "courses.json", function( json ) {
            for (var key in Object.keys(json)) {
                var btn = document.createElement("BUTTON");
                document.getElementById("nav").appendChild(btn);
                btn.id = "myBtn";
                $.each(json[key], function(index, course) {
                    var btns = document.createElement("BUTTON");
                    document.getElementById("myBtn").appendChild(btns);
                })
            }
        })
    })
...

Alternatively, modify the initial for loop so that it iterates through both the array of courses and the key "i". This can be accomplished using $.each, similar to what you've done in another part of your code:

...
    $( document ).ready(function() { 
        $.getJSON( "courses.json", function( json ) {
            $.each(json, function(key, semester_courses) {
                var btn = document.createElement("BUTTON");
                document.getElementById("nav").appendChild(btn);
                btn.id = "myBtn";
                $.each(semester_courses, function(index, course) {
                    var btns = document.createElement("BUTTON");
                    document.getElementById("myBtn").appendChild(btns);
                })
            })
         })
    })
...

These adjustments should help resolve your issue. If you encounter any further errors, feel free to leave a comment and I will update my response. Additionally, please remember to include the latest version of your code that is causing the error. Thank you!

Answer №2

In the scenario where `semester1` and similar properties are the only ones present in the primary JSON object:

$(function(){ // initialization
$.getJSON('courses.json', function(data){
  $.each(data, function(semester, courseArray){
    $.each(courseArray, function(index, courseObj){
      var button = document.createElement('input');
      button.type = 'button'; 
      button.id = semester+'_'+index; 
      $('#myButton').append(button);
      $(button).on('click', function(){
        console.log(courseObj); 
      });
    });
  });
});
}); // end of initialization

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

Display a specific section depending on the user's input by utilizing either ng-if or ng-show

I have a scenario where I need to display one of two sections based on user input. If the user selects 'Daily' in the first 'type' input, I want section 1 to appear (Enter start date and hour). For any other type selection, I want secti ...

Convert a list to XML and JSON with Jackson serialization

I have a scenario where I need to serialize a class to both JSON and XML: @JacksonXmlRootElement(localName = "devices") class DeviceWrapper { // <-- this class is intended to provide root xml name @JacksonXmlProperty(localName = "dev ...

Using the React context without explicitly setting the contextType or defining a default context

Is it possible to access the closest context from a provider without having to explicitly define contextType in a component by using this.context? Alternatively, is there a way to establish a default context so that when I use this.context, I automaticall ...

Sending variables to other parts of the application within stateless functional components

My main component is Productos and I also have a child component called EditarProductos. My goal is to pass the producto.id value from Productos to EditarProductos. Here is my Productos component code: import {Button, TableHead, TableRow, TableCell, Tabl ...

When the DOM elements have already been rendered, document.querySelector() will return null

I have been working on creating an automated Puppeteer script to download my monthly bank transactions from the bank's website. However, I have encountered a strange error (refer to the attached Imgur link for images of this issue) https://i.sstatic ...

Is it possible to align a div on the same line with an h1 header that spans multiple lines using CSS?

I am currently working on the following code: <h1><span>Test Heading This is the text that I want to display on the right side. This is the text that I want to display on the right side. This is the text that I want</span></h1> < ...

Obtain the contenteditable span's value

I'm facing an issue with a content editable span - I want to extract its value when the post button is clicked, but it's not working as expected. Please note that I am unable to convert the span to a textbox or div, I specifically need the value ...

Combining two JSON objects with sailsjs-nodejs to create a single merged object

Hello everyone, I am a beginner with Sailsjs-Nodejs. Currently, I have two JSON Objects in my controller that I need to merge/join in order to create a third object to send as a response. The output when using res.send(obj1) is: [ { total_fare: "37 ...

What is the best way to style .json files using Brackets?

While attempting to edit files for various programs that I am downloading, I have noticed that most of them utilize .json files. I have tried to open these files using Atom, Notepad++, Sublime Text Editor 3, and Brackets. However, when I open them, all of ...

Transforming javascript's array.map into php's array_map function

The following code snippet is written in JavaScript and consists of a hashmap array with keys and values. I have created a function using map that returns the values of the entered keys. var rule = { "c": "d", "a": "o", "t": "g", "h": "a", "e": "n", "n": ...

What is the best way to handle errors in the front-end when receiving responses from expressjs?

Here is the issue that I am facing: //express server app.post('/register', (req, res) => { const { password, passwordConfirm } = req.body; if (password === passwordConfirm) { //... } else { ...

"Utilize Excel VBA function to generate an array and directly input it into a worksheet

Can a VBA function return array values and paste them in an Excel sheet using a formula? For instance, I would like to enter the formula =GetData() in cell A1 of an Excel spreadsheet and have it populate cells A1:A4 and B1:B4 with 4 different metrics. I ...

Generate a Year attribute value using the information from the year field in a JSON document

Currently, I am exploring the functionalities showcased in this example: I am interested in adapting the following code snippet to work with my JSON file, which lacks a specific date data type field but includes a 'Year' value: // Transform Yea ...

jQuery failing to trigger onClick event for a specific group of buttons

Javascript: <script> $(document).ready(function(){//Implementing AJAX functionality $(".acceptorbutton").on('click', function(){ var whichClicked = this.attr('name'); ...

Problem with integrating React Hook Forms with Material UI Autocomplete in React app

I'm struggling with integrating React Hook Forms with Material UI Components, and I'm having trouble finding resources on how to do this. On a page where I fetch countries and current profile information, I want to display it inside a form. My in ...

Incorporating image hyperlinks onto a designated webpage within a JavaScript presentation carousel

Working on an e-commerce website, the client has requested 3 slide shows to run simultaneously displaying specials or promotions. I have successfully set up the 3 slide shows next to each other, but I'm unsure how to incorporate image links that direc ...

CKEditor's height automatically increases as the user types

I am using a ckEditor and looking for a way to make its height automatically grow as I type. https://i.stack.imgur.com/m7eyi.png <textarea name="description" id="description"> </textarea> <script> CKEDITOR.replace( 'description ...

Expanding and collapsing multiple div elements easily with Javascript code

I am exploring how to customize the expand/collapse functionality for multiple DIVs on my webpage. Currently, I have implemented a code snippet that toggles an entire class, but I am wondering if there is a way to target the specific element being clicked ...

Experiencing an "isTrusted" error while working with the GLTFLoader

QUERY: All was running smoothly: I successfully transformed my FBX files to GLTF in the /GLTF/ directory. Unfortunately, after noticing missing geometry in some converted files, I attempted another conversion of the FBX files, this time to /TEST/. Unexp ...

PHP - A guide to inserting an array at a specific index

I need help inserting an array at a specific index in PHP. For example: Array ( [0] => Array ( [music_id] => 2 [m_title] => Rolling In The Deep [m_cover_image] => [m_file_path] ...