Adding an item to an array in AngularJS: A step-by-step guide

Here is a snippet of code I have been working on:

$scope.studentDetails=[];

   $scope.studentIds={};
   $scope.studentIds[0]{"id":"101"}
   $scope.studentIds[1]{"id":"102"}
   $scope.studentIds[2]{"id":"103"}

Within the above code, when I select student id:101, I receive marks from services like:

   $scope.studentMarks={};
   $scope.studentMarks[0]{"marks":"67"}
   $scope.studentMarks[1]{"marks":"34"}

Next, when I select student id:102, I get marks from services as follows:

   $scope.studentMarks={};
   $scope.studentMarks[0]{"marks":"98"}
   $scope.studentMarks[1]{"marks":"85"}

Ultimately, my goal is to store student details in an array like this:

$scope.studentDetails=[{"id":"101","marks":[67,34]},{"id":"102","marks":[98,85]}] 

And I am achieving this using AngularJS.

Answer №1

It appears that this question is more related to JavaScript rather than Angular.

Have you considered using the JavaScript push method?

$scope.updateStudentDetails.push({studentID: 201, scores: [89, 45]});

Answer №2

One way to expand an array is by utilizing the Array.extend function, which can append a single object or merge one array into another. Check out the provided resources for more information.

Answer №3

angularJS is a powerful tool that enhances the functionality of Javascript. By utilizing angularJS, you can easily manipulate arrays just like any other object in Javascript.

To begin, it is essential to initiate an array.

$scope.userIds = []; // Array of user ids.

Once the array is declared, you can add elements by using the push method:

$scope.userIds.push({id: "202"});

Answer №4

If you want to achieve this in a straightforward manner, you can iterate through the student IDs first and then go over the marks dataset to populate the studentDetails object only when the IDs match:

var studentDetails = [];

for (var id in studentIds) {
    var studentDetail = {}; // represents a single student
    var marks = [];    

    if (studentIds.hasOwnProperty(id)) {
        for (var mark in studentMarks) {
            if (studentMarks.hasOwnProperty(mark) && mark.id === id) {
                studentDetail.id = id;
                marks.push(mark.marks);
            }
        }
        studentDetail.marks = marks;
    }
    studentDetails.push(studentDetail);
}

$scope.studentDetails = studentDetails;

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

Is it possible to transfer a specific index value from one array to another?

My goal is to extract specific values from a particular index in one array and copy them to another array using the following code snippet: for (int i = 0; i < 100; i++) { if ([subID[i] isEqual: @"0"]) { NSLog(@"state : %@",arrayTe ...

What is the best way to record data while initiating a process in node.js?

In my latest project, I have implemented a function that spawns a process and requires logging specific information to the console. Here is an example of how this function is structured: function processData(number) { var fileName = settings.file || "de ...

use ajax to post saved data to a WebAPI in php

I have successfully implemented the code to save data in a custom table using Ajax. Now, I need to figure out how to send this data to an asp.Net API using js/jQuery. How can I achieve this? Below is my HTML form and JS code: <div id="inline1" class= ...

How can elements be collapsed into an array using the Reactive approach?

Consider this TypeScript/Angular 2 code snippet: query(): Rx.Observable<any> { return Observable.create((o) => { var refinedPosts = new Array<RefinedPost>(); const observable = this.server.get('http://localhost/ra ...

Error encountered: Unspecified "from" address in the provided or default options

Seeking guidance on a project related to Ethereum and Solidity, part of Udemy's course titled "Ethereum and Solidity: The Complete Developers Guide." I am currently working on building the front-end for a Kickstarter alternative. I am facing an issue ...

Troubleshooting problem: AJAX autocomplete URL returning XML

I found my code reference here: http://example.com/code-reference if ($hint=="") { $hint="<a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes-> ...

Update the radio button to display the value entered in the text input field

I'm trying to implement a feature where the value of a text box can be set as the value of the selected radio button. Below is the code I have: HTML <form action="add.php" id="registration" method="post" name='registration' onsubmit="re ...

Vue JS: Easily Calculate the Total Sum of All Columns

An example of a query in the backend controller public function show($id) { $structural = DB::table('attendance')->where('payroll_daily_id',$id) ->where('assignment','STRUCTURAL') -&g ...

What is the best way to preserve changes made to DOM manipulation?

Within my controller code, there is a section that removes a specific DOM element: MetrofficeApp.controller('EmployeesCtrl', function($scope) { ... angular.element(deleteElem).remove(); $scope.$apply(); However, when I navigate away from the pa ...

Creating a dynamic model in an AngularJS directive using a JSON object

I am struggling with utilizing a json file that contains objects storing properties for a directive. Despite my attempts, I cannot seem to access the json obj model value within the directive. Does anyone have any insights into what I might be doing incor ...

Troubleshooting and Fixing AJAX Calls

When working with Asynchronous JavaScript, it is common to encounter issues where we are unsure of the posted request and received response. Is there a simple method for debugging AJAX requests? ...

Trouble with fill() function

Check out this JavaScript code snippet I wrote: function Show(output, startX, startY){ var c = document.getElementById("myCanvas"); var context = c.getContext("2d"); context.arc(startX, startY, 3, 0, Math.PI*2, true); context.fill( ...

Guide on detecting errors when parameters are not provided with req.params in Node.js

My question revolves around a piece of code that I have been working on. Here is the snippet: const express = require('express') const app = express() app.get('/test/:name', (req, res) => { const {name} = req.params; res.send(`P ...

Interested in mastering BootStrap for Angularjs?

As a PHP developer with a newfound interest in JavaScript, I took it upon myself to learn AngularJS and jQuery. However, I recently discovered that simply mastering Angular is not enough - Bootstrap is also necessary. My only issue is my fear of CSS; handl ...

Using an if statement following the iteration of a JSON object in a React Native application

I am currently working on a weather app using react native as a fun project. I have set up an API to fetch weather data in JSON format. My goal is to show the hourly weather details based on the current time of the day. export default class App extends ...

Avoiding page refresh while submitting a form can be tricky, as both e.preventDefault() and using a hidden iFrame seem

I've been stuck on this issue for a while now, scouring Stack Overflow and Google for solutions, but nothing seems to be working. My main goal is to avoid page reloads after uploading a file because it resets the dynamic HTML I need to display afterwa ...

PHP regular expression /only match 10 whole digits/;

Currently, I am working on updating a PHP script that contains the following code snippet: function CheckNumber(MyNumber) { var MN = /^\d{10}$/; if (MN.test(MyNumber)) { return true; } return false; } The current script enfor ...

Wait for NodeJS to finish executing the mySQL query

I am attempting to send an object from the controller to the view. To keep my queries separate from the controller, I am loading a JS object (model). My model structure is as follows: function MyDatabase(req) { this._request = req; this._connection = ...

What is the best way to prevent the dropdown function in a selectpicker (Bootstrap-Select)?

Is there a way to completely disable a selectpicker when a radio button is set to "No"? The current code I have only partially disables the selectpicker: $("#mySelect").prop("disabled", true); $(".selectpicker[data-id='mySelect']").addClas ...

Issue encountered while trying to implement a recursive function for mapping through nested elements was not producing the

I am currently working on recursively mapping through an array of nested objects, where each object can potentially contain the same type of objects nested within them. For example: type TOption = { id: string; name: string; options?: TOption; } con ...