In NetSuite scripting, saved searches are a powerful tool for retrieving data. However, using built-in filters in a saved search every time you need to retrieve specific data can be limiting, especially when you want to manipulate or reuse the data multiple times in a script. Instead, you can fetch the entire dataset once, store it, and then filter it dynamically using JavaScript’s .filter() function.
This approach allows greater flexibility and reduces the need to repeatedly execute saved searches, saving governance units and improving performance.
Why Use JavaScript’s .filter() Instead of Built-in Filters?
- Flexibility: JavaScript’s
.filter()provides more complex filtering capabilities compared to NetSuite’s saved search filters. - Efficiency: Fetch the data once and reuse it multiple times without executing the saved search again.
- Performance: Reduces the number of saved search executions, saving governance units.
- Customization: Apply custom filtering logic based on conditions that might not be supported natively in saved searches.
Steps to Store and Filter Saved Search Results
Step 1: Fetch and Store the Data
Retrieve the results of the saved search and store them in an array for reuse.
Step 2: Apply JavaScript’s .filter() Method
Use the .filter() method on the stored array to retrieve only the records that meet specific conditions.
Example Implementation
Here’s how you can store the results of a saved search and later filter them using JavaScript.
Fetching and Storing Results
/**
* @NApiVersion 2.x
* @NScriptType UserEventScript
*/
define(['N/search', 'N/log'], function(search, log) {
function beforeSubmit(context) {
// Fetch and store all results of a saved search
var allResults = [];
var itemSearch = search.create({
type: search.Type.ITEM,
filters: [], // No filters applied here; fetch all relevant data
columns: [
'internalid',
'displayname',
'custitem_category', // Example custom field
'custitem_stockstatus' // Example custom field
]
});
itemSearch.run().each(function(result) {
allResults.push({
id: result.getValue('internalid'),
name: result.getValue('displayname'),
category: result.getValue('custitem_category'),
stockStatus: result.getValue('custitem_stockstatus')
});
return true; // Continue fetching results
});
log.debug('All Results', allResults);
// Store the data in memory (or a custom record if needed for later use)
return allResults;
}
return {
beforeSubmit: beforeSubmit
};
});
Filtering the Data Using .filter()
After storing the results, apply custom logic with .filter() to retrieve specific subsets of data.
/**
* Filter stored results to get items in a specific category and stock status
*/
function filterResults(allResults) {
// Example: Filter items belonging to category "Electronics" and in stock
var filteredResults = allResults.filter(function(item) {
return item.category === 'Electronics' && item.stockStatus === 'In Stock';
});
log.debug('Filtered Results', filteredResults);
return filteredResults;
}
Full Integration Example
define(['N/search', 'N/log'], function(search, log) {
function beforeSubmit(context) {
// Step 1: Fetch and store all results
var allResults = [];
var itemSearch = search.create({
type: search.Type.ITEM,
filters: [],
columns: [
'internalid',
'displayname',
'custitem_category',
'custitem_stockstatus'
]
});
itemSearch.run().each(function(result) {
allResults.push({
id: result.getValue('internalid'),
name: result.getValue('displayname'),
category: result.getValue('custitem_category'),
stockStatus: result.getValue('custitem_stockstatus')
});
return true;
});
log.debug('All Results', allResults);
// Step 2: Filter results using JavaScript
var filteredResults = allResults.filter(function(item) {
return item.category === 'Electronics' && item.stockStatus === 'In Stock';
});
log.debug('Filtered Results', filteredResults);
// Process the filtered results (e.g., update fields, log data)
filteredResults.forEach(function(item) {
log.debug('Processing Item', item.name);
// Additional logic here
});
}
return {
beforeSubmit: beforeSubmit
};
});
Benefits of This Approach
- Reusability: The data can be filtered in different ways without re-executing the saved search.
- Efficiency: Reduces the need for redundant saved search executions, saving script governance units.
- Custom Filtering: Allows applying conditions that are more complex than the standard saved search filters.
- Better Debugging: You can log the entire dataset and filtered subsets for detailed analysis during script execution.
Tips for Implementation
- Batch Large Data: If the saved search returns a very large dataset, consider batching the results to avoid memory issues.
- Store Data Locally: Use script-level variables to store the results. If you need persistence, save the data to a custom record or cache.
- Optimize Filters: Write efficient
.filter()conditions to minimize processing time. - Error Handling: Ensure the
.filter()logic accounts for undefined or null values to avoid runtime errors.
Conclusion
Storing saved search results and dynamically filtering them with JavaScript’s .filter() is a powerful way to optimize your NetSuite scripts. It not only improves performance by reducing the number of saved search executions but also adds flexibility to apply complex filtering logic. This approach is particularly useful when processing large datasets or handling scenarios where multiple filters need to be applied dynamically.