What is the best way to transform an array of arrays into an array of objects using AngularJS?

Here is some code I am working on:

$scope.students=[];

$scope.students[[object Object][object Object]]
               [0]{"id":"101","name":"one","marks":"67"}
               [1]{"id":"102","name":"two","marks":"89"}

I would like to reformat it into the following structure.

$scope.students=[{"id":"101","name":"one","marks":"67"},{"id":"102","name":"two","marks":"89"}]

I attempted to use the .map function but it did not work as expected. Now I am looking for a way to convert an array of arrays into an array of objects using AngularJS.

Answer №1

Assume the variable students is a two-dimensional array like this:

students = [[{"id":"101","name":"one","marks":"67"}, {"id":"102","name":"two","marks":"89"}]]

To extract each object from the arrays within students and store them in another array, you can use a nested loop in vanilla JavaScript. Below is an example, but there are alternative methods to achieve the same result.

var students = [];
var results = [];

students = [[{"id":"101","name":"one","marks":"67"}, {"id":"102","name":"two","marks":"89"}]]

console.log(students); //array of arrays
console.log('-----'); 
console.log(students[0]); //array of objects
console.log('-----'); 
for (i = 0; i < students.length; i++) { 
    console.log(students[i]); //the array of objects

  for(var j=0; j < students[i].length; j++){
    results.push(students[i][j]);  
  }
}

console.log('--Results---');
console.log(results);

You can also view my code on JSBin: https://jsbin.com/tareku/edit?html,js,console

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

How to Handle 404 Errors for Specific Express Routes and Not Others

Struggling with the setup of a single page app using Angular routes on the front end, while facing backend issues. All database-related routes are functional, but any additional route designed to serve an HTML file or simple text like "hello world" result ...

Invoke Javascript through CSS selector

On my webpage, I have implemented a mousemove-mask feature that was inspired by an existing codepen. However, there is one significant issue that I can't seem to resolve on my own. Despite my attempts to fix it, I believe someone with more expertise c ...

Learn the technique of hovering over an image to see it blur and reveal overlay text

Currently, I am in the process of creating my portfolio website and after experimenting with some code, I was able to achieve the desired outcome. <div id="nytimes" class="portfolio-thumbnail" style="left: 100px; top: 80px;"> <span class="text ...

Cheerio's method of extracting data from an HTML table using web scraping

Currently, I am facing an issue with a web scraping project. The specific webpage that I am attempting to scrape looks something like this: <table style="position..."> <thead>..</thead> <tbody id="leaderboard_body"> ...

A guide to accessing array elements (JSON) in Angular

Having a variable named $scope.informationData, the data appears like this when outputted by console.log: {"completed":100,"pending":50,"defects":20,"overdue":10} However, when trying to display just the "overdue" value in my HTML using the following cod ...

Combining various components within an inactive element tag using Vue

I am working on creating expandable rows for a table element using this HTML code snippet. The current approach involves alternating between parent rows and multiple rows within tbody elements. <tbody class="js-table-sections-header">Parent row</ ...

immutable chrome sqlite data objects

I have been utilizing a sqlite DB as the storage system for a web application. I have been directly using the objects returned from queries in my application. For instance: function get_book_by_id(id,successCallback,errorCallback) { function _successC ...

Issue: Access to sdcard/hello.mp3 file denied due to permission error (EACCES)

While testing the "react-native-audio-recorder-player": "^3.5.3" on Android 11 & 12 with targetSDKversion 31, I encountered the error message Error: sdcard/sound.mp3: open failed: EACCES (Permission denied). Numerous suggested solut ...

Implementation of asynchronous code in event handlers is necessary

In my AngularJS controller, I have implemented an event mechanism to communicate with external elements. One particular event is triggered to retrieve the URL where the data should be sent. The event handler reacts to this event by making an AJAX call usi ...

Encountering the 401 (Unauthorized) error while attempting to delete data in loopback?

I have a model called companyUsers and when I send a GET request, I am able to retrieve all the data successfully. However, when I try to make a DELETE or PUT request, I encounter a 401 (Unauthorized) error. For example, I made a DELETE request using the ...

Acquiring data from a separate Redux slice and utilizing it as the default state in a distinct slice

In my application, I have two Redux slices called userSlice and cartSlice. My goal is to extract the specific value userName from the userSlice and use it as the initial value for a property named user in the cartSlice. Despite my efforts, I am encounterin ...

Yeoman - A guide for integrating an express server task into Gruntfile.js from the generator-angular template

Currently, I am diving into the world of Grunt and attempting to integrate an Express server into my AngularJS application that was initially created with Yoeman. I've made adjustments to the following task as shown below: grunt.registerTask('s ...

Get the image from the express route

Currently, I am running an express server with the following route: exports.getUserFile = function (req, resp) { let filePath = path.join(__dirname, 'storage', req.params.fileName); resp.download(filePath); }); } Within my web app ...

Calculating the total of fields from populated documents using Mongoose

In my application, I have two main models: User and Track. A User can complete various Tracks and earn points for each one. The schema for the User model looks like this: let userSchema = new mongoose.Schema({ name: {type: String, required: true}, ...

JavaScript menu that pops up

Hello everyone, I've recently created an HTML5 file that, when clicked on a specific href link, is supposed to display an image in a smooth and elegant manner. However, so far it hasn't been working for me as expected. Instead of smoothly popping ...

Display a div based on search results

I recently encountered an issue with a script that needs modification to display different divs based on search criteria. Originally, I used this script for a contact list but now need it to perform another function. View the original code (JSFiddle) Here ...

I am encountering an issue with the return ( statement and I'm unable to comprehend the reason behind it

import { connect } from 'react-redux' import { Link } from 'react-router-dom' class MyFavoriteStories extends React.Component { markAsFavorite = (e) => { this.setState({ bgColor: "blue" }) } render () { con ...

The total height of an HTML element, which takes into account the margin of the element itself

Is there a way to accurately calculate the height of an element including margins, even when dealing with child elements that have larger margins than their parents? HTMLElement.offsetHeight provides the height excluding margin, while this function from ...

While loop not yielding immediate result with asynchronous function

As a beginner in Node.js, I have successfully connected an LCD Panel and a 4x4 Membrane matrix keypad to my Raspberry Pi. Using Node.js, I have programmed them to work together. My goal is to have the LCD panel immediately display any key pressed on the ke ...

Tips for transferring data from a pop-up or modal window to the main window in ASP.NET MVC

Currently, I am in the process of developing a contact form within ASP.NET MVC. This contact form will allow users to easily attach regular files through traditional file and browse functions. Additionally, users will have the option to search for a specif ...