search
HomeWeb Front-endJS TutorialCreate data reports using javascript function

Assume you have a sporting event or competition. Most likely the results will be stored in a database and have to be listed on a website. You can use the Fetch API to fetch the data from the backend. This will not be explained in this document. I assume the data has already been retrieved and is an array of records. This array of records has to be in the correct order, but the source function can filter and sort the array on the fly within the report engine.

This document decribes how to define headers and footers very easily and how to arrange record grouping by compare function as well.

Each header function returns html based on static text and parameters currentRecord, objWork and splitPosition. Each footer function returns html based on static text and parameters previousRecord, objWork and splitPosition.

It is very flexible, but you have to make the html yourself! Don't expect a WYSIWYG editor.

General structure of a report

  • Report has a report header and footer. Can be text or just html or both.
  • Report has one or more section levels. Section level N starts with header level N and ends with footer level N.
  • Section level N contains one or more times section level N 1, except the highest section level.
  • Highest section level contains the data created based on the records in the array. In most cases highest section level is just a html table or html flex item.

Example of report structure

Create data reports using javascript function

Structure of report definition object called reportDefinition

const reportDefinition = {};
reportDefinition.headers = [report_header, header_level_1, header_level_2, header_level_3, ...]; // default = []
reportDefinition.footers = [report_footer, footer_level_1, footer_level_2, footer_level_3, ...]; // default = []
reportDefinition.compare = (previousRecord, currentRecord, objWork) => {
    // default = () => -1
    // code that returns an integer (report level break number)
};
reportDefinition.display = (currentRecord, objWork) => {
    // code that returns a string, for example
    return `${currentRecord.team} - ${currentRecord.player}`;
};
// source array can be preprocessed, for example filter or sort
reportDefinition.source = (arr, objWork) => preProcessFuncCode(arr); // optional function to preprocess data array
// example to add extra field for HOME and AWAY and sort afterwards
reportDefinition.source = (arr, objWork) => arr.flatMap(val => [{ team: val.team1, ...val }, { team: val.team2, ...val }])
    .sort((a, b) => a.team.localeCompare(b.team));
// optional method 'init' which should be a function. It will be called with argument objWork
// can be used to initialize some things.
reportDefinition.init = objWork => { ... };

Examples of headers and footers array elements

reportDefinition.headers = [];
// currentRecord=current record, objWork is extra object,
// splitPosition=0 if this is the first header shown at this place, otherwise it is 1, 2, 3 ...
reportDefinition.headers[0] = (currentRecord, objWork, splitPosition) => {
    // code that returns a string
};
reportDefinition.headers[1] = '<div>Some string</div>'; // string instead of function is allowed;
reportDefinition.footers = [];
// previousRecord=previous record, objWork is extra object,
// splitPosition=0 if this is the last footer shown at this place, otherwise it is 1, 2, 3 ...
reportDefinition.footers[0] = (previousRecord, objWork, splitPosition) => {
    // code that returns a string
};
reportDefinition.footers[1] = '<div>Some string</div>'; // string instead of function is allowed;

Example of compare function

// previousRecord=previous record, currentRecord=current record, objWork is extra object,
reportDefinition.compare = (previousRecord, currentRecord, objWork) => {
    // please never return 0! headers[0] will be displayed automagically on top of report
    // group by date return 1 (lowest number first)
    if (previousRecord.date !== currentRecord.date) return 1;
    // group by team return 2
    if (previousRecord.team !== currentRecord.team) return 2;
    // assume this function returns X (except -1) then:
    // footer X upto and include LAST footer will be displayed (in reverse order). In case of footer function the argument is previous record
    // header X upto and include LAST header will be displayed. In case of header function the argument is current record
    // current record will be displayed
    //
    // if both records belong to same group return -1
    return -1;
};

Running counter

In case you want to implement a running counter, you have to initialize/reset it in the right place. It can be achieved by putting some code in the relevant header:

reportDefinition.headers[2] = (currentRecord, objWork, splitPosition) => {
    // this is a new level 2 group. Reset objWork.runningCounter to 0
    objWork.runningCounter = 0;
    // put extra code here
    return `<div>This is header number 2: ${currentRecord.team}</div>`;
};

If you only want to initialize objWork.runningCounter at the beginning of the report you can achieve that by putting the right code in reportDefinition.headers[0]. I call it property runningCounter, but you can give it any name you want.

You have to increase the running counter somewhere in your code because... otherwise it is not running ;-) for example:

const reportDefinition = {};
reportDefinition.headers = [report_header, header_level_1, header_level_2, header_level_3, ...]; // default = []
reportDefinition.footers = [report_footer, footer_level_1, footer_level_2, footer_level_3, ...]; // default = []
reportDefinition.compare = (previousRecord, currentRecord, objWork) => {
    // default = () => -1
    // code that returns an integer (report level break number)
};
reportDefinition.display = (currentRecord, objWork) => {
    // code that returns a string, for example
    return `${currentRecord.team} - ${currentRecord.player}`;
};
// source array can be preprocessed, for example filter or sort
reportDefinition.source = (arr, objWork) => preProcessFuncCode(arr); // optional function to preprocess data array
// example to add extra field for HOME and AWAY and sort afterwards
reportDefinition.source = (arr, objWork) => arr.flatMap(val => [{ team: val.team1, ...val }, { team: val.team2, ...val }])
    .sort((a, b) => a.team.localeCompare(b.team));
// optional method 'init' which should be a function. It will be called with argument objWork
// can be used to initialize some things.
reportDefinition.init = objWork => { ... };

How to create totals for multiple section levels, a running total and even a numbered header

reportDefinition.headers = [];
// currentRecord=current record, objWork is extra object,
// splitPosition=0 if this is the first header shown at this place, otherwise it is 1, 2, 3 ...
reportDefinition.headers[0] = (currentRecord, objWork, splitPosition) => {
    // code that returns a string
};
reportDefinition.headers[1] = '<div>Some string</div>'; // string instead of function is allowed;
reportDefinition.footers = [];
// previousRecord=previous record, objWork is extra object,
// splitPosition=0 if this is the last footer shown at this place, otherwise it is 1, 2, 3 ...
reportDefinition.footers[0] = (previousRecord, objWork, splitPosition) => {
    // code that returns a string
};
reportDefinition.footers[1] = '<div>Some string</div>'; // string instead of function is allowed;

How to preprocess the source array on the fly (for example in click event)

// previousRecord=previous record, currentRecord=current record, objWork is extra object,
reportDefinition.compare = (previousRecord, currentRecord, objWork) => {
    // please never return 0! headers[0] will be displayed automagically on top of report
    // group by date return 1 (lowest number first)
    if (previousRecord.date !== currentRecord.date) return 1;
    // group by team return 2
    if (previousRecord.team !== currentRecord.team) return 2;
    // assume this function returns X (except -1) then:
    // footer X upto and include LAST footer will be displayed (in reverse order). In case of footer function the argument is previous record
    // header X upto and include LAST header will be displayed. In case of header function the argument is current record
    // current record will be displayed
    //
    // if both records belong to same group return -1
    return -1;
};

How to generate the report

reportDefinition.headers[2] = (currentRecord, objWork, splitPosition) => {
    // this is a new level 2 group. Reset objWork.runningCounter to 0
    objWork.runningCounter = 0;
    // put extra code here
    return `<div>This is header number 2: ${currentRecord.team}</div>`;
};

Source code

Below source code I created to make this all work. It is kind of wrapper function for all headers and footers. Feel free to copy paste it and use it in your own module.

reportDefinition.display = (currentRecord, objWork) => {
    objWork.runningCounter++;
    // put extra code here
    return `<div>This is record number ${objWork.runningCounter}: ${currentRecord.team} - ${currentRecord.player}</div>`;
};

What is objWork

objWork is a javascript object that is passed as the second argument to createOutput function (optional argument, default {}). It is passed on as shallow copy to headers functions, footers functions, compare function, init function, source function and display function. All these functions share this object. You can use it for example for configuration information or color theme. objWork is automagically extended with { rawData: thisData }. For example createOutput(reportDefinition, { font: 'Arial', font_color: 'blue' }).

Examples

The examples listed below are written in Dutch.
Reports for billiard club
Reports for billiard scores
More reports for carom billiards
Reports for petanque
and many more....

The above is the detailed content of Create data reports using javascript function. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software