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

Encountering issues with compiling files in react app using webpack, failing to compile as anticipated

When it comes to compiling, I prefer using webpack with TypeScript files. In my webpack.config.js file: module.exports = async (env, options) => { const dev = options.mode === "development"; const config = { //Webpack configuration pr ...

What is the best way to manage a JSON feed that does not provide any results?

Excuse my lack of experience as I pose my first question. Using FullCalendar 5.10.1, I am working on retrieving events dynamically associated with Festivals. I have followed the 'events (as a json feed)' pattern from the documentation. When ther ...

Converting XML attributes to JSON using Java

Having a bit of trouble converting an XML file with attributes to JSON. Specifically, there is an issue with the BvdState attribute that is causing the conversion to fail. Not quite sure what steps to take in order to resolve this issue. <State> ...

Customizing URLs in AngularJS using ui-router allows for more personalized

Hey there, I've encountered an issue with my app. Users can sign up as merchants and have their own store name with a URL structure like this: http://localhost:8000/#/storename The problem arises when the default homepage subpages, such as contactus ...

Utilizing unique layouts for specific views in sails.js and angular.js

I am currently working on a Sails.js + Angular.js project with a single layout. However, I have come across different HTML files that have a completely different layout compared to the one I am using. The layout file I am currently using is the default la ...

Speedily deliver a message to the designated destination

I have a specific route set up at /test: app.route('/test', (req,res)=>{ res.sendFile(__dirname + "\\myhtml.html") }) Now, I want to trigger an event in Node.js on the /test route, and have myhtml.html file listen for ...

Which type of encoding does json.dumps utilize?

While utilizing json.dumps in Python 3.8, I noticed that special characters are getting "escaped", like so: >>> import json >>> json.dumps({'Crêpes': 5}) '{"Cr\\u00eapes": 5}' I am curious to know ...

Using Node.js to automatically update a geojson file on a map through dynamic file reading process

In my current project, I am utilizing NodeJs (ExpressJS) and AngularJS for the front-end. One of the features includes displaying geoJSON polygons on a map, with the color of the polygon being determined by real-time data from a file that may be updated ev ...

Scroll upwards within a nested div

Is there a way to smoothly animate the content of the inner div upward without requiring any button clicks? Also, is there a method to trigger an event once the animation has completed? ...

Solving Angular Circular Dependencies

My popupservice allows me to easily open popup components: export class PopupService { alert() { this.matdialog.open(PopupAlertComponent); } yesno() { this.matdialog.open(PopupYesNoComponent); } custom() { this.matdialog.open(PopupCustomCompon ...

What is the reason behind JavaScript's `fn.length` returning the count of named parameters that `fn` function has?

Why does calling fn.length in JavaScript return the number of named arguments fn has? > function fn () { } > x.length 0 > function fn (a) { } > x.length 1 > function fn (a,b,c) { } > x.length 3 This behavior is quite peculiar. I wonde ...

Retrieve the URL for the React component

I'm facing some challenges with React fundamentals :/ I have a piece of code that creates a table using JSON data: import React from 'react' import { DataTable } from 'react-data-components'; function createTable(data) { ...

Issue with conflicting trigger events for clicking and watching sequences in input text boxes and checkboxes within an AngularJS application

When creating a watch on Text box and Check box models to call a custom-defined function, I want to avoid calling the function during the initial loading of data. To achieve this, I am using a 'needwatch' flag inside the watch to determine when t ...

How to ensure that the iframe is completely loaded before proceeding with Selenium JavaScript

I have a webpage that displays an iframe, within the iframe there is a spinning spinner (overlying the fields). My approach involves using selenium to navigate to the iframe, return this.driver.wait(function() { return self.webdriver.until.ableToSw ...

Implement a feature in JavaScript that highlights the current menu item

I'm currently developing a website at and have implemented a JavaScript feature to highlight the current menu item with an arrow. The issue I'm facing is that when users scroll through the page using the scrollbar instead of clicking on the men ...

Testing controllers in AngularJS with units

Unit testing in AngularJs has been a bit confusing for me as I am just getting started with it. The syntax seems unusual to me, especially when writing tests for a controller. Here is an example code snippet: describe('PhoneCat controllers', fun ...

"Enhance Your Video Experience with a Personalized Play Button

Is it possible to customize the play icon for an embedded YouTube video? I came across a post discussing this topic: Can I change the play icon of embedded youtube videos? However, when trying to use something transparent as the new play button, the origin ...

The importance of understanding Req.Body in NODE.JS POST Requests

Currently, I am developing a Node.JS application that interacts with a MySQL database. The app retrieves data from the database and displays it in a table using app.get, which functions correctly. The issue I am facing is that when utilizing app.post, re ...

Is there a Django application that can dynamically create forms based on JSON data?

I'm in the process of developing a Django website and I am interested in incorporating dynamically generated forms based on JSON data fetched from an external source. For example, consider the following JSON structure: [ { "name": "first ...

Converting the output to JSON format for archival purposes

Having trouble writing my output to a JSON file in the correct format. The code og = OpenGraph(i, ["og:title", "og:description", "og:image", "og:url"]) is not producing valid JSON. Can someone point out what I'm doing wrong? # -*- coding: utf-8 -*- i ...