Converting a JSON array into a table using AngularJS

Here is the structure of my JSON data:

[{"Name":["A","B","C","D","E","F"], "Age":["20","30","40","50","55","60"], "Gender":["M","M","F","M","Unknown","Unknown"]}]

I am looking to create an AngularJS table that resembles the following format:

Name    Age     Gender
A       20      M
B       30      M
C       40      F

Most examples I have found show JSON data in a different format, such as:

[
    {Name: "A",     Age: "20",  Gender: "M"},
    {Name: "Bag",   Age: "30", Gender: "F"},
    {Name: "Pen",   Age: "40",  Gender: "F"}
];

I'm unsure how to proceed with transforming my JSON data. Can anyone provide guidance on this?

Answer №1

If your property arrays are all of equal length and properly organized, you can leverage the $index feature within an ng-repeat loop.

<table>
    <thead>
        <tr>
            <td>Name</td>
            <td>Age</td>
            <td>Gender</td>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="name in obj.Name">
            <td>{{name}}</td>
            <td>{{obj.Age[$index]}}</td>
            <td>{{obj.Gender[$index]}}</td>
        </tr>
    </tbody>
</table>

Another approach (assuming well-structured data) involves consolidating the separate lists into a single array of person objects using JavaScript. You can then proceed as demonstrated in other examples.

The JavaScript code may be structured like this:

$scope.people = [];
obj.Name.forEach(function(name, index) {
    people.push(
    {
        Name: name,
        Gender: obj.Gender[index],
        Age: obj.Age[index]
    });
});

You can now simply use an ng-repeat on the new people array to display the content.

 ...
    <tbody>
        <tr ng-repeat="person in people">
            <td>{{person.Name}}</td>
            <td>{{person.Age}}</td>
            <td>{{person.Gender}}</td>
        </tr>
    </tbody>

Answer №2

Give it a shot.

<div ng-repeat="person in people.Names">
  Name: {{person}} Age: people.Ages[$index] Gender: people.Genders[$index]
</div>

I'm assuming your data is organized and ordered.

Answer №3

Utilize the lodash function _.zip to organize them into an array, and use _.map to transform it into JSON objects by utilizing a custom function:

var rows = _.zip(users.Name, users.Age, users.Gender);  // [["A",20,"M"],...]
$scope.users = 
    _.map(rows, function(row) {
        return {Name: row[0], Age: row[1], Gender: row[2]}
    });

Then, loop through them to retrieve values:

<table ng-controller="UsersTableController">
    <thead>
        <th>NAME</th>
        <th>AGE</th>
        <th>GENDER</th>
    </thead>
    <tbody>
        <tr ng-repeat="user in users">
            <td>{{user.Name}}</td>
            <td>{{user.Age}}</td>
            <td>{{user.Gender}}</td>
        </tr>
    </tbody>
</table>

For more information, visit: https://lodash.com/docs#zip , https://lodash.com/docs#map

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

Tips for avoiding quotation mark issues in JSON in Microsoft Flow?

My MS Flow creates an Adaptive Card from a new Planner task, but it fails when the task title contains double quotes. This causes issues with the json code for the Adaptive Card. I attempted to use the @replace function directly in the json code, but it d ...

Is it possible for Angular Parent & Child Scope to function properly within the $root scope?

I came across two examples showcasing parent and child scope inheritance. The first example utilizes parent and child controllers, while the second example relies on root scope. Interestingly, the second example does not produce the expected results. What ...

What is the best way to activate an alert or swal function just once instead of repeatedly?

I am just starting to learn Angular. Currently, I have an application that contains two variables related to the status of financial transactions. These variables are: tab1TrxMessage, which holds any important messages, and tab1TrxStatus that indicates wh ...

Instruction not activating

Within my main.controller.js, I have a basic json object named $scope.sections. $scope.sections = [ { id: "landing", description: "<div><img pinch-zoom src='public/img/model.png'></div>" } ]; In the vie ...

What is the best way to populate an array with unique values while applying a condition based on the objects' properties?

Looking to create a unique exam experience for each student? I have an array of question objects and the goal is to select random and distinct questions from this array until the total sum of scores equals the specified exam score. This means that every s ...

Tips for creating a map within an array and including it in a JSON file using Go

My goal is to create a sign-up server using Go where user information is stored in a JSON file named users.json with the following structure: [ { "email": "email", "password": "password" }, ...

Using Vue.js to handle asynchronous functions with undefined variables

My Vue.js application is facing a problem where an async function is passing a variable as undefined even though it's properly defined before the function call. The async function FETCH_DATA in my Vue.js application is defined like this: async [FETCH ...

Converting Cyrillic characters to ASCII codes using JavaScript: A step-by-step guide

Is there a reliable method to convert characters from the CP1251 table to ASCII codes ranging from 0 to 255? So far, I have only come across the charCodeAt() function which is limited to codes up to 128. It returns a Unicode number for codes above that r ...

Toggle menu using jQuery to show and hide options

I'm currently working on a menu that should open when the button is clicked once and close when clicked again. I had done this before but I seem to have forgotten how to achieve it. Here is the code snippet that I tried to use: var main = function() ...

Axios removes the async functionality

Is there a way to achieve the same functionality without using the async function? async EnvioLogin() { const response = await axios.post("api/auth/login", { email: this.email, password: this.password, }); localStorage.setItem(" ...

Discover siblings in React component siblings

Creating a parent element (Board) that generates a list of children and provides a method to access this list can be done like so: export default class Board extends React.Component { constructor(props) { super(props); this.getList = t ...

Unable to retrieve the email addresses of Facebook users using the Facebook JavaScript SDK

Utilizing the Facebook authentication feature on my website through javascript sdk, I am able to retrieve my own email and name. However, when users log in, only their names are accessible (since it's linked to my fb developer app). Despite prompting ...

Function that contains a JavaScript reference and observation

I'm experiencing issues with the code below and I'm having trouble figuring out what's causing the problem. function some(){ for (var i=0;i<....;i++) { var oneObject; ...some logic where this object is set oneObject.watch(prop ...

The Carousel Slider seems to encounter issues when trying to implement it with *ngFor in Angular 8

Currently tackling an issue in Angular 8 where my slider functions perfectly with static data. However, upon attempting to loop through some dynamic data, the 'left' and 'right' buttons on the carousel cease to work. The images also fai ...

Converting a Non-Specific Collection to JSON in C#

Encountering an issue while inserting data into a collection. I need to input some data into the collection and then convert it into JSON in a specific format. The problem arises when I cannot achieve my desired JSON output. While a dictionary collection ...

When attempting to POST data in Laravel, a status of 419 (unknown) is returned and the data cannot be posted to the target URL

I am attempting to create a DOM event that triggers when a user clicks on a table row's header (th) cell, deleting the corresponding row from the database that populates the table. Previously, my code worked as expected without any framework. I simpl ...

What is the best way to configure a metered subscription plan on Stripe that invoices annually but bills extra fees for overage on a monthly basis

I'm in the process of setting up a subscription system on stripe that includes a plan with 5000 monthly credits for a flat $299 yearly fee. My goal is to charge customers who exceed their monthly credit limit by the end of each month. For example, if ...

Error: CSRF token cookie is missing [Django/AngularJS]

Let me start by clarifying that this question is not a duplicate. Despite scouring through numerous related posts on stackoverflow, I have been unable to find a resolution. I am grappling with an issue in my setup where I have a Django backend and Angular ...

Convert the output of get_post_meta() into a JSON format

I am seeking assistance in converting the generated data from get_post_meta into JSON format. The array that was generated looks like this: Array ( [0] => Array ( [0] => Array ( [0] => A ...

What are the benefits of utilizing a timeout?

I've recently started working with AngularJS and the angular-datatable library. One problem I am facing is how to trigger a modal to pop up when a row is clicked. Here's a snippet of my code: function rowCallback(nRow, aData, iDisplayIndex, iDis ...