Developing a data table with JavaScript by parsing JSON data

Looking to generate a school timetable table using dummy JSON data. The JSON object structure is as follows:

this._days=[
     {
           "day": "",
           "config": {}
        },

        {
           "day": "Monday",
           "config": {
               'timing': [
                   {'time': '9:00AM-10:00AM', 
                   'schedule': {'subject': 'Physics','teacher': 'Amanda','Location': 'Room 05'}
                   },
                   ...
                ]
            }
        },...

Want the table to dynamically adjust based on any changes in the JSON object size or structure. The ideal layout resembles a typical school timetable with days as headers and time slots down the left column. A basic hardcoded example has been created:

<table width="100%" align="center" height=100%;>
        <tr class="day">
            <th>Time</th>
            <th>Monday</th>
            <th>Tuesday</th>
            ...
        </tr>

        <tr class="time">
            <th>10:00 - 11:00</th>
            ...
        </tr>
        
        ...

An attempt was made using Angular 2 (typescript) :

<div>
    <table style="width:100%; height:200px;">
        <tr>
            <th *ngFor="let row of _days" style="background: grey; color:white"> 
                <h3><b>{{row.day}}</b></h3>
            </th>
        </tr>
        <tr *ngFor="let row of _days">
            <td style="background: grey;color:white">
                <h3><b>{{row.config.timing[row].time}}</b></h3>
            </td>
        </tr>
    </table>
</div>

Need guidance on implementing this using JavaScript or Angular 2 (TypeScript). Thank you!

Answer №1

If you want to utilize the primeng datatable component in your Angular 2 application, follow these steps:

Firstly, in your module, import the necessary modules:

import {DataTableModule,SharedModule} from 'primeng/primeng';

Next, in your HTML file, include the following code snippet:

<p-dataTable [value]="cars">
    <p-column field="vin" header="Vin"></p-column>
    <p-column field="year" header="Year"></p-column>
    <p-column field="brand" header="Brand"></p-column>
    <p-column field="color" header="Color"></p-column>
</p-dataTable>

Lastly, in your component file, define the data fetching logic as shown below:

public cars: Car[];

constructor(private http: Http) { }

ngOnInit() {
    this.http.get('data.json')
    .map(res => res.json())
    .subscribe(data => this.cars = data,
                err => console.log(err),
                () => console.log('Completed'));
}

For more information on using PrimeNG datatable in Angular 2, visit https://www.primefaces.org/primeng/#/datatable

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

Exploring Nested Views in a MEAN Application using UI Router

I am currently developing a MEAN application and struggling to get my ui-router functioning correctly. Within my index.html template, I have loaded all the necessary javascript and css for my application such as angular, jquery, angular-ui-x, bootstrap. I ...

Shopping cart has encountered an issue with storing the data correctly

While I've managed to successfully integrate another service, the challenge now lies in implementing the logic for correctly generating cart items. My goal is to increment the quantity of items in the cart by one with each function call, but it seems ...

Executing a C# program that sends a web request without using JavaScript

My goal is to programmatically download the contents of a website, but it seems like this content is being loaded through ajax calls. Interestingly, when I disable javascript in my browser, only one request is made by the page and all the content is displa ...

Prevent selection of future dates in JavaScript by using the user's chosen StartDate

Here is the code I currently have: var today = new Date().toISOString().split('T')[0]; document.getElementsByName("StartDate")[0].setAttribute('min', today); $('#StartDate').change(function myfunction() { var endDate = ...

What steps can I take to make sure that a sub component's props are refreshed properly?

I'm encountering an issue with RTK queries in my project. I have a parent component that contains a table component. When a refresh event occurs, such as deleting data, the parent component receives updated data and passes it down to the child compone ...

Managing the activation and deactivation of a form based on value modifications

I have a formgroup with interconnected formcontrols where each control is enabled only if the previous one is filled. Additionally, if a control is cleared, all subsequent controls should also be cleared and disabled. To illustrate this use case, I create ...

A guide to effectively converting and parsing a class object that includes Uint8Array elements

After stringifying a class object that contains a property in Uint8Array, and then parsing it later, the property is no longer in Uint8Array format. Here's an example: class Example { title:string; byteData:Uint8Array; ...

Updating specific entity attributes in Hibernate can be done by selectively modifying only certain parts of an entity's

After receiving a JSON containing 30 fields, I construct my entity based on this information. However, there are two specific fields that should not be updated (two dates). The issue arises when using entity.merge, as it results in both fields being updat ...

Encountering a Runtime Exception while setting up a Client Component in the latest version of Next JS (v13.3

I am facing an issue with a component in my Next JS website. When I attempt to convert it into a Client Component, the page fails to load in the browser and I encounter the following unhandled runtime exception: SyntaxError: "undefined" is not va ...

Exploring JQuery Autocomplete and Optimizing JSON Parsing

I have experience in programming, but I'm new to working with Javascript and JQuery. I'm struggling to determine where to parse the JSON results I receive after making an AJAX query for JQuery's autocomplete feature. Here is the code I hav ...

The Angular firestore is showing an error stating that the property 'toDate' is not found in the 'Date' type

I am currently working on converting a timestamp object from Firestore to a Date object in TypeScript by utilizing the toDate() method. import { AngularFirestore } from '@angular/fire/firestore'; ... constructor(private database?: AngularFirestor ...

Declaring TypeScript functions with variable numbers of parameters

Is it possible to define a custom type called OnClick that can accept multiple types as arguments? How can I implement this feature so that I can use parameters of different data types? type OnClick<..> = (..) => void; // example usage: const o ...

What happens with JQuery if the JQuery IIFE does not get executed properly?

The jquery-3.3.1.js file contains the following code: ( function( global, factory ) { ... } ); Within this Immediately-Invoked Function Expression (IIFE), there is a line allowing for the use of the JQuery and $ variables to call the JQuery function: wi ...

What causes the namespace to shift when utilizing npm for installing a library?

I've been attempting to integrate whammy.js into a project. The initial line in the source code is window.Whammy = (function(){ yet, after running npm i and inspecting node_modules, I discovered global.Whammy = (function(){ https://github.com/anti ...

I'm attempting to utilize AJAX to modify the sorting and ordering arguments in a WP_Query, yet I'm struggling to pinpoint the reason behind the failure of my code

After hours of non-stop work, about 6 solid hours with no breaks, I am baffled as to why this code isn't working. Let's take a look at the form in question: <div id="wp-ajax-filter-search" class="full"> <form ...

reading an array of objects using typescript

Trying to retrieve an object from an array called pVal. pVal is the array that includes objects. I am attempting to obtain the value of "group" based on the id provided. For instance, if the id is equal to 1, it should display "VKC". Any assistance woul ...

JavaScript allows for the creation of animated or timed text

Here is the code snippet I am currently working with: function list() { return "blob1<br>blob2<br>blob3"; } When I run this code, it simply displays all the text in return at once when the function is called. I am wondering if there is a ...

Updating state from multiple handlers using the useReducer hooks in React: a complete guide

Currently, I am utilizing { useReducer } to handle the state of my form. Nonetheless, I have two distinct handlers: handleChange() = used for input changes (this one is functioning as intended) const handleChange = async (e) => { dispatch({fiel ...

The response from a jQuery ajax call to an MVC action method returned empty

I am working on an inventory application with the following layout: <body> <div class="container" style="width: 100%"> <div id="header"> blahblahblah </div> <div class="row"> <div id="rendermenu ...

Multiple consecutive XHR requests failed without any error message. The cause remains unknown

Here is the content of my package.json file: canActivate in my code:</p> imports: [ BrowserModule, FormsModule, ReactiveFormsModule, RouterModule.forRoot([ {//route configs path: '', redirectTo: '/cfbsetup', pathMatch: &a ...