display.grid.forEach()
Description
display.grid.forEach() runs the provided function once for each record in the grid, in order. It is modeled on the JavaScript Array.prototype.forEach() method and is useful for calculating totals, logging, or performing an action for every record.
The record passed to the function is a copy, so changing it does not change the grid. To change every record, use display.grid.applyMap() instead.
Syntax
display.gridName.forEach(callback)Parameters
Callback (Function) - The function to run for each record. It receives the following arguments:
Record (Object) - A copy of the current grid record, with one property for each field in the grid. Changing this object does not change the record in the grid.
Index (Number) - The zero-based index of the record being processed.
Records (Array) - The array of all grid records that is being processed.
Return Value
Nothing is returned.
Examples
Example 1: Total a Column
Adds up the quantity of every record. The same result can be produced with display.grid.reduce().
Prerequisite: a Rich Display File named display.json with a record format named screen that contains a grid whose record format name is mygrid, with the fields product, description, and quantity bound to its columns.
pjs.defineDisplay("display.json"); // Object name defaults to "display"; display.json defines mygrid
// Load four records into the grid so there is something to work with
display.mygrid.replaceRecords([
{ product: 1, description: "ITEM ONE", quantity: 15 },
{ product: 2, description: "ITEM TWO", quantity: 20 },
{ product: 3, description: "ITEM THREE", quantity: 12 },
{ product: 4, description: "ITEM FOUR", quantity: 18 }
]);
// Add the quantity of each record to a running total
var total = 0;
display.mygrid.forEach(function(record) {
total += record.quantity;
});
console.log(total); // 65Example 2: Use the Index Argument
Prints a numbered list of the records. The index is zero-based, so 1 is added to produce line numbers that start at 1.
Prerequisite: a Rich Display File named display.json with a record format named screen that contains a grid whose record format name is mygrid, with the fields product, description, and quantity bound to its columns.
pjs.defineDisplay("display.json"); // Object name defaults to "display"; display.json defines mygrid
// Load three records into the grid so there is something to work with
display.mygrid.replaceRecords([
{ product: 1, description: "ITEM ONE", quantity: 15 },
{ product: 2, description: "ITEM TWO", quantity: 20 },
{ product: 3, description: "ITEM THREE", quantity: 12 }
]);
display.mygrid.forEach(function(record, index) {
console.log((index + 1) + ". " + record.description + " (qty " + record.quantity + ")");
});
// The lines above log:
// 1. ITEM ONE (qty 15)
// 2. ITEM TWO (qty 20)
// 3. ITEM THREE (qty 12)