Manipulating nested JSON objects with AngularJS by adding and pushing the data

I am looking at a JSON object structured like this :

{
    "Name": "Shivansh",
    "RollNo": "1",
    "Stream": "CSE",
    "OverallScore": "76",
    "Semester": [
        {
            "SemesterName": "FY-2012 - 1",
            "TotalScore": "78.00",
            "StartDate" : "2012-02-14",
            "EndDate" : "2012-07-16",
            "Amount" : "55000",
            "Subject": [
                {
                    "subjectname": "maths",
                    "score": "81"
                },
                {
                    "subjectname": "chemistry",
                    "score": "79"
                },
                {
                    "subjectname": "physics",
                    "score": "77"
                }
            ]
        },
        {
            "SemesterName": "FY-2013-1",
            "TotalScore": "76.00",
            "StartDate" : "2013-02-16",
            "EndDate" : "2014-07-16",
            "Amount" : "55000",
            "Subject": [
                {
                    "subjectname": "ADA",
                    "score": "80"
                },
                {
                    "subjectname": "Operating System",
                    "score": "77"
                },
                {
                    "subjectname": "Databases",
                    "score": "73"
                },
                {
                    "subjectname": "Economics",
                    "score": "71"
                }
            ]
        }                
    ]
}

Now I want to insert another semester field into this JSON using angularJS. Is there anyone who can guide me on how to achieve this? The new semester field that needs to be added could look something like this:

{
                    "SemesterName": "FY-2013-2",
                    "TotalScore": "75.00",
                    "StartDate" : "2011-02-16",
                    "EndDate" : "2012-07-16",
                    "Amount" : "55067800",
                    "Subject": [
                        {
                            "subjectname": "Sets and Probability",
                            "score": "78"
                        },
                        {
                            "subjectname": "Networking and Security",
                            "score": "76"
                        },
                        {
                            "subjectname": "Advanced DataBases",
                            "score": "72"
                        },
                        {
                            "subjectname": "Economics-2",
                            "score": "70"
                        }
                    ]
                }

Currently, my controllers have this structure:

$scope.addRowSubject = function() {
            $scope.insertsub = {
                //id = $scope.getSubject.length+1;
                subjectname : '1',
                score : '1'
            };

            $scope.getSubject.push($scope.insertsub);
};

getSubject represents the list of subjects within one semester field. This list can be accessed without any issues.

$scope.addRowSemester = function() {
            $scope.insertsem = {
                //id = $scope.getSemester.length+1;
                StartDate : "1",
                EndDate : "1",
                Amount : "1",
                SemesterName : "1",
                TotalScore : "1",
                Subject : ""
            }
$scope.getSemester.push($scope.insertsem);
};

getSemester holds the list of Semesters for a student.

Although I can successfully add a semester field to my JSON, the Subject field remains null preventing me from adding subjects. Any suggestions on this issue would be appreciated. Thank you in advance.

Answer №1

To properly define the subject properties of your jsonObject, it is important that it be an instance of an array as illustrated below:

$scope.addRowSemester = function() {
            $scope.insertsem = {
                //id = $scope.getSemester.length+1;
                StartDate : "1",
                EndDate : "1",
                Amount : "1",
                SemesterName : "1",
                TotalScore : "1",
                Subject : []
            }

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

Performing a series of synchronous JavaScript calls in Node.js by executing GET requests within a for loop

I'm utilizing super-agent in node to interact with a public API and I'm curious if there's a way to make synchronous calls using it. Although I appreciate its automatic caching feature, my research online suggests that synchronous calls are ...

The issue of JQuery $(this) malfunctioning when used within a function parameter

Encountering an issue with the code snippet below: $(".countdown").circularCountdown({ startDate:$(this).attr('data-start'), endDate:$(this).attr('data-end'), timeZone:$(this).attr("timezone") }); On the contrary, the co ...

The specified function 'isFakeTouchstartFromScreenReader' could not be located within the '@angular/cdk/a11y' library

I encountered the following errors unexpectedly while working on my Angular 11 project: Error: ./node_modules/@angular/material/fesm2015/core.js 1091:45-77 "export 'isFakeTouchstartFromScreenReader' was not found in '@angular/cdk/a11y&a ...

Align the image in the middle using JavaScript for Firebase

I am struggling to display the center of an image within a circle-shaped <img> tag with a border-radius of 50%. The issue arises when trying to display an image fetched from Firebase storage, rather than from a URL. In attempt to solve this problem, ...

Securing uploaded documents and limiting access to approved individuals

Currently, I am utilizing Multer for file uploads and I am contemplating the ideal approach to secure access to these files post-upload. In my system, there are two user roles: admin and regular user. Users can only upload photos while only admins have ac ...

Obtain the parameter value from the resolve function in ui-router

Using window.open, I plan to open a URL such as https://localhost:3000/new?HostId=8Ocs_Onuv1wowozxAAAS&_host_Info=excel%7Cweb%7C16.00%7Cen-us%7Cc8b501ce-c51d-b862-701e-5c623e1a70e0%7CisDialog. The site https://localhost:3000 hosts a MEAN stack applica ...

Trigger an Ajax function using a button within a Bootstrap modal

I need to trigger an ajax function after selecting an option from a bootstrap confirmation modal. The modal will appear by calling the remove(parameter) function. Any assistance would be greatly appreciated function remove(parameter){ // $("#remove-mod ...

React Component Functions for Export and Import

Currently working on a webapp built with React. My main component is defined in App.js, while I have another subcomponent responsible for creating buttons, like the logout button generated by renderLogoutButton(). But now, I want to reuse this function in ...

How to retrieve nested menu items within the scope by utilizing JSON and AngularJS

I have recently started working with angular and am facing difficulty in accessing the submenu items within my angular application. While I can successfully access the top level menu items, I am struggling to retrieve the second level items. Here is a sni ...

Hmm, JavaScript is throwing a JSON parse error related to single quotes. But where exactly is

When using an upload php script with AS3 and now with JavaScript, I encountered a test feature that should return this if everything is okay: {"erro":"OK","msg":"","descr":"op:ini,urlArq:\/Library\/WebServer\/Documents\/www\/sintr ...

What is the best way to extract the text from a class only when it is nested within a particular header tag?

const request = require ('request'); const cheerio = require('cheerio'); const fs = require ('fs'); request("http://kathmandupost.ekantipur.com/news/2018-08-31/bimstec-summit-multilateral-meet-underway.html", (error, response ...

What is the best way to transfer a variable to an isolated scope function?

I have set up a directive as shown below - <div data-my-param-control data-save-me="saveMe()"></div> Within the directive controller, I have connected the saveMe() function from the controller to an isolated scope like so - function MyParam ...

Modifying paragraph content with JavaScript based on selected radio button values and troubleshooting the onclick event not triggering

I am working on implementing a language selection feature on my website where users can choose between English and Spanish. The idea is to have two radio buttons, one for each language, and a button. When the button is clicked, the text of the paragraphs s ...

The Javascript regex allows for the presence of positive and negative numbers, with the option of a single minus symbol

oninput="this.value = this.value.replace(/[^-0-9.]/g, '') This code snippet is utilized in my current project. However, there seems to be an issue where the input can contain more than one minus sign, as shown here: ---23 To address this p ...

Choosing an option from a dropdown menu by extracting information from JSON content

My goal is to develop a basic jQuery plugin that interacts with a geolocation system to provide data on the location of the user's IP address and then automatically select the corresponding country in an HTML form. Within my HTML code, I have a selec ...

Preserving data in input fields even after a page is refreshed

I've been struggling to keep the user-entered values in the additional input fields intact even after the web page is refreshed. If anyone has any suggestions or solutions, I would greatly appreciate your assistance. Currently, I have managed to retai ...

How to Use a Discord Bot to Send a Message (Step-by-Step Guide)

I am looking for a simple way to send a message using my discord bot, but everything I have found online seems too complex for me to understand and implement. require("dotenv").config(); //to start process from .env file const { Client, GatewayIn ...

How do I overwrite this calculation using JQuery?

I have a website: link There are two pages on my site that have the same div elements... I want one page to perform a certain calculation on the divs, and another page to perform a different calculation... New JavaScript Code: jQuery(document).ready(fu ...

Tips for effectively showcasing JSON in an Angular directive

I am facing an issue with my Angular app that utilizes ui-router. I have set up a service and directive, but I am unable to display JSON data. Surprisingly, it works perfectly fine without the directive when I directly display it in the main template (home ...

How can I use nodejs to retrieve all data fields from a table except for one specific field?

Is there a way to fetch all fields data from a table without specifying the field names or creating a view? I have attempted the following SQL query: WITH orderschema as (SELECT array_to_string(ARRAY(SELECT c.column_name FROM information_schema.co ...