A guide to populating a table with JSON data that includes empty cells in AngularJS

I'm dealing with JSON data that includes employee names and salaries over multiple days (1-5). My goal is to display this information in an HTML table using AngularJS, mimicking the layout of the required table below.

JSON Data:

[{
        name: "John",
        salaryBreakdown: [{
                day: 1,
                salary: 32
            }, {
                day: 2,
                salary: 40
            }, {
                day: 5,
                salary: 105
            }
        ]
    }, {
        name: "Nick",
        salaryBreakdown: [{
                day: 1,
                salary: 27
            }, {
                day: 4,
                salary: 82
            }
        ]
    }, {
        name: "Bob",
        salaryBreakdown: [{
                day: 2,
                salary: 55
            }, {
                day: 3,
                salary: 80
            }
        ]
    }
]

Required Table:

Name     Day1     Day2     Day3     Day4     Day5
-------------------------------------------------
John       32       40        -        -      105
Nick       27        -        -       82        -
Bob         -       55       80        -        -

The challenge I face is how to handle empty cells in the table when certain days have no salary entries (e.g. days 3 and 4 for John). One approach is to add zero-salary objects for every day in the salaryBreakdown array of each employee, but this could be inefficient and redundant. Is there a way to achieve the desired view without modifying the JSON data? The current HTML setup I've used falls short of meeting my needs.

Current HTML (incorrect):

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Day1</th>
            <th>Day2</th>
            <th>Day3</th>
            <th>Day4</th>
            <th>Day5</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="employee in jsonData">
            <td ng-bind="employee.name"></td>
            <td ng-repeat="item in employee.salaryBreakdown | orderBy: 'day'" ng-bind="item.salary"></td>
        </tr>
    </tbody>
</table>

Current Table (incorrect):

Name     Day1     Day2     Day3     Day4     Day5
-------------------------------------------------
John       32       40      105
Nick       27       82
Bob        55       80

Answer №1

To insert blank objects into a new array, you can use the following code:

data.forEach(item => {
  item.newArray = [];
  for (let j = 1; j <= 10; j++) {
    let obj = item.existingArray.find(o => o.id === j) || {"id": j, "value": ""};
    item.newArray.push(obj);
  }
});

Check out this demo on JSFiddle: https://jsfiddle.net/X4321qwe/22/

Answer №2

One approach is to simplify the salary arrays by organizing them into single objects with days as keys, enabling easy lookup of each person's salary based on the day

angular
  .module('app', [])
  .controller('myCtrl', function($scope) {
    $scope.data = angular.copy(data);
    $scope.data.forEach(o => o.salaryBreakdown = o.salaryBreakdown.reduce((a, c) => {
      a[c.day] = c;
      return a
    }, {}))

    
    $scope.days = [1,2,3,4,5]
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>


<table ng-app="app" ng-controller="myCtrl">
    <thead>
        <tr>
            <th>Name</th>
            <th>Day1</th>
            <th>Day2</th>
            <th>Day3</th>
            <th>Day4</th>
            <th>Day5</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="employee in data">
            <td ng-bind="employee.name"></td>
            <td ng-repeat="day in days" ng-bind="employee.salaryBreakdown[day].salary ||0 "></td>
        </tr>
    </tbody>
</table>


<script>
var data =[{
        name: "John ",
        salaryBreakdown: [{
                day: 1,
                salary: 32
            }, {
                day: 2,
                salary: 40
            }, {
                day: 5,
                salary: 105
            }
        ]
    }, {
        name: "Nick ",
        salaryBreakdown: [{
                day: 1,
                salary: 27
            }, {
                day: 4,
                salary: 82
            }
        ]
    }, {
        name: "Bob ",
        salaryBreakdown: [{
                day: 2,
                salary: 55
            }, {
                day: 3,
                salary: 80
            }
        ]
    }
]
</script>

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

Collapse the mobile nav bar upon clicking an item

I'm currently facing a challenge with the navigation bar on my event landing page. The issue is that when I open the navbar in mobile view, it does not collapse back after clicking on an item. Instead, it remains open and covers almost 3/4 of the scre ...

Uh-oh: create-react-app installation has been canceled

As per the guidelines provided in Reactjs documentation: To start a new project, you must have Node version >= 8.10 and npm version >= 5.6 installed on your system. Use the following command to create a project: npx create-react-app my-app My envir ...

Retrieving Data from a JSON File in ASP.NET MVC 4

After diving into learning ASP.NET MVC 4, I dabbled in some small projects... On my index page, my goal is to fetch a JSON file containing data and showcase it on the main page. In basic HTML and JavaScript, I utilize ajax for fetching or posting JSON da ...

Overlaying images with cropped elements

When uploading an image on a webpage, I want to display a preview of the image. I am looking to create an overlay that showcases the image in a rectangle at the center, surrounded by a semi-transparent background outside the rectangle. Something resemblin ...

Angular = encountering an incorrect array size limitation

I am encountering an issue with the function in my controller... $scope.pagerPages = function (n) { var i = Math.ceil(n); return new Array(i); } The n value is derived from an expression on the view and can sometimes be a fraction. This is why I ...

The process of incorporating JSON data into the database is experiencing difficulties and is not functioning

I am looking to display the doctor's availability in my Laravel project using JSON to show the availability in both morning and afternoon time slots. Initially, it was working fine, but now it only displays the last added time slot like this: Monday_m ...

Combining input streams using node.js and ffmpeg

Currently, I'm in the process of developing a basic and straightforward Video-Web-Chat platform. My approach involves utilizing the getUserMedia API call on the client side to capture webcam data and transmit it as data-blob to my server. My plan is ...

The functionality of my website is currently experiencing difficulties when accessed through the Android UC Browser

My website, , is experiencing issues with product loading and the '+' button in the side menu not working on UC Browser. It works fine on other Android browsers like Chrome and Firefox, but I am confused as to why it is not functioning properly o ...

Remove the initial section of the text and provide the rest of the string

I am a beginner in the world of Javascript and unfortunately I have not been able to find an answer to my current problem. Here is the situation. On a webpage, I am receiving a URL that is sometimes presented in this format: http://url1.come/http://url2.c ...

Retrieving data from a file results in receiving blank strings

Struggling to access the data within a directory of files, I've encountered an issue where the data doesn't seem to be read correctly or at all. Even though there is content when opening the files individually, when attempting to examine their co ...

Tips for implementing a regular expression in JavaScript to parse tags from a Docker image?

I recently came across this regex for parsing docker image tag in Python. ^(?P<repository>[\w.\-_]+((?::\d+|)(?=/[a-z0-9._-]+/[a-z0-9._-]+))|)(?:/|)(?P<image>[a-z0-9.\-_]+(?:/[a-z0-9.\-_]+|))(:(?P<tag>[\w.&bs ...

Ways to verify if a component triggers an event in VueJS

I am currently working with two components within my application. The Child component emits an 'input' event whenever its value is changed, and the Parent component utilizes v-model to receive this updated value. In order to ensure that the funct ...

Guide to displaying JSON.stringify data in PHP

I am attempting to retrieve my Google contact list using the Contact API. I have successfully retrieved the result and it is displaying in the console of both Chrome and Firefox browsers. However, I want to print this data using PHP on the same page. < ...

Can someone show me how to implement arrow functions within React components?

I am facing an issue while working on a node and react project. Whenever I use an arrow function, it shows an error stating that the function is not defined. Despite trying various tutorials and guides, I am unable to resolve this issue. Below is the snipp ...

What is the method to retrieve a JSON array without specifying an array name?

Need assistance in retrieving data from the server using JSON, as the array name is missing. I am unfamiliar with this JSON format, please guide me through the process. Below is my Java code: class JSONAsyncTask extends AsyncTask<String, Void, Boolean ...

Utilize the bodyParser middleware within a middleware to handle the request body parsing

Currently, I am developing an Express app where most routes have a limited body size except for admin users who require unlimited body size for certain routes. To manage this, I implemented a middleware called limitBodySize using the following syntax: app. ...

Error encountered during JSON object conversion

How can I convert the string below into an object? "{"taskStatus":"Not Started","taskFields":{"originalTransactionDate":"${datafield:feerefund:originalTranDate}","transactionPostingDate":"${datafield:feerefund:tranPostingDate}","referenceNumber":"${data ...

Jest's JavaScript mocking capability allows for effortless mocking of dependent functions

I have developed two JavaScript modules. One module contains a function that generates a random number, while the other module includes a function that selects an element from an array based on this random number. Here is a simplified example: randomNumbe ...

Adjust the value before moving to the next tab, or if you choose to leave the

Looking for help to display a popup message when a user edits any value? Check out this resource that I found. It currently only triggers when moving to another page, but I need it to work within an Ajax tab system as well. Here is the code I have tried: ...

Encountering Difficulty Accessing Index.ejs with Express.js

Currently, I am enrolled in a Linkedin course that focuses on building websites using express.js. I have encountered an issue where my index.ejs page is not rendering properly, as the server keeps loading my index.html page instead. I have tried searching ...