Attempting to generate a nested array structure in order to produce a JSON object for output

I am currently working on a JavaScript script that interacts with the Netsuite ERP platform to retrieve data.

Currently, the script is returning data in an array format, specifically product information. While this is functional, I would prefer it to return multiple arrays of arrays to simplify external content handling outside of Netsuite.

The script is querying for 3 products, resulting in an array with 21 keys. Ideally, it should return 3 separate arrays of arrays instead.

I am struggling to determine which loop structure is needed to create these new arrays for better content management.

function loadRecord(request, response)
{
    var recType = request.getParameter('recType');
    var savedSearchId = request.getParameter('savedSearchId');
    var internalid = request.getParameter('internalid');
    
    // Perform the required search.
    var filter = [];
    
    if(recType == 'customer' || recType == 'contact' )
    {
        filter[0] = new nlobjSearchFilter('internalid', null, 'is', internalid);
    }

    if( recType == 'item')
    {
        var internal_ids = [25880, 25980, 333];
        filter[0] = new nlobjSearchFilter('internalid', null, 'anyOf', internal_ids);      
    }


    if(recType == 'transaction')
    {       
        filter[0] = new nlobjSearchFilter('type',null,'anyOf','SalesOrd');
        filter[1] = new nlobjSearchFilter('internalid','customer','is', internalid );
    }

    var rsResults = nlapiSearchRecord(recType, savedSearchId, filter);
    var rsObj = [];

     // Unsure about how to restructure the data into nested arrays for more elegant organization...
    for (x = 0; x < rsResults.length; x++)
    {
        var flds = rsResults[x].getAllColumns();

        for (i = 0; i < flds.length; i++)
        {
            var rowObj = {};
            rowObj.name = flds[i].getName();
            rowObj.label = flds[i].getLabel();
            rowObj.val = rsResults[x].getValue(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary());
            rowObj.txtval = rsResults[x].getText(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary())            
            rsObj.push(rowObj);
        }
    }
    response.write(JSON.stringify(rsObj));
}

Any assistance would be greatly appreciated.

Answer №1

Are you seeking this information?

var resultObj = [];
var rowData, availableFields, x, y;

for (x = 0; x < resultset.length; x++)
{
    fields = resultset[x].getAllColumns();

    for (y = 0; y < fields.length; y++)
    {

        rowData = resultObj[x] = [];
        rowData.push(fields[y].getName());
        rowData.push(fields[y].getLabel());
        rowData.push(resultset[x].getValue(fields[y].getName(), fields[y].getJoin(), fields[y].getSummary()));
        rowData.push(resultset[x].getText(fields[y].getName(), fields[y].getJoin(), fields[y].getSummary()));
    }
}

console.log(resultObj[0][0]); // row0.name
console.log(resultObj[2][1]); // row2.label

Answer №2

Perhaps consider the following approach:

for (var x = 0; x < rsResults.length; x++)
{
    var fields = rsResults[x].getAllColumns();

    for (var i = 0; i < fields.length; i++)
    {
        rsObj.push({
            name: fields[i].getName(),
            label: fields[i].getLabel(),
            val: rsResults[x].getValue(fields[i].getName(), fields[i].getJoin(), fields[i].getSummary()),
            txtval: rsResults[x].getText(fields[i].getName(), fields[i].getJoin(), fields[i].getSummary())
        });
    }
}

If you're using ECMAScript5, you could streamline the loop with forEach, as shown below:

rsResults.forEach(function(result) {
    result.getAllColumns().forEach(function(flds) {
        rsObj.push({
            name: flds.getName(),
            label: flds.getLabel(),
            val: result.getValue(flds.getName(), flds.getJoin(), flds.getSummary()),
            txtval: result.getText(flds.getName(), flds.getJoin(), flds.getSummary())
        });
    });
});

Answer №3

If you're facing a problem, this solution should help. It might be related to declaration issues.

var rsObj = [];

for (let x = 0; x < rsResults.length; x++)
{
    let flds = rsResults[x].getAllColumns();

    for (let i = 0; i < flds.length; i++)
    {

        let rowObj = [];
        rowObj.push(flds[i].getName());
        rowObj.push(flds[i].getLabel());
        rowObj.push(rsResults[x].getValue(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary()));
        rowObj.push(rsResults[x].getText(flds[i].getName(), flds[i].getJoin(), flds[i].getSummary()));            

        rsObj.push(rowObj);
    }
}

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

Mastering Backbone views and router functionality is essential for building scalable and efficient web

In my code, I have a series of page states that mimic the steps of a shopping cart checkout process. The first set of code sets up the ItemsCollection, ItemsView, and ItemsApp in Backbone.js. var ItemsCollection = Backbone.Collection.extend({ model: I ...

What is the best method for designing a custom mask for the jQuery Masked Input Plugin that accommodates alphanumeric characters, spaces, and accented

Looking for a way to make a custom mask in jQuery Masked Input Plugin that allows alphanumeric characters, spaces, and accented characters? This is what I currently have: $.mask.definitions["A"] = "[a-zA-Z0-9 ]"; $("#input").mask("A?AAAAAAA"); However, ...

Tips for maintaining state URL persistence after a page refresh in Next.js 13 when utilizing next-usequerystate

Currently, I am using the next-usequerystate library with Next Js 13. However, I have encountered an issue where the state on the URL is lost when I refresh the page. The initial URL looks like this: localhost:3000/?page=1&genres=tree But upon refres ...

prettyPhoto popup exceeds maximum width and height limitations

I am currently using the most up-to-date version from No Margin for Errors and I have set allow_resize to true. However, the size of the display is still too large. Is there a way to set a maximum width/height? I have already configured the viewport as fo ...

Unable to redirect with Asp response.redirect

I have a Login popup form where I use an ajax post request to Login.asp script in order to prevent the page from going to the POST URL after submission. <script> $(function() { $('#contactForm').submit(function(e){ e.preventDe ...

The index declaration file has not been uploaded to NPM

After creating a Typescript package and publishing it on NPM, I encountered an issue with the declaration files not being included in the published version. Despite setting declaration: true in the tsconfig.json, only the JavaScript files were being publis ...

One way to clear out a directory in Node.js is to delete all files within the directory while keeping

Can anyone guide me on how to delete all files from a specific directory in Node.js without deleting the actual directory itself? I need to get rid of temporary files, but I'm still learning about filesystems. I came across this method that deletes ...

Revamping JSON structure by identifying id references

I recently attempted to update the city name within the JSON object provided below. "City":[ { "Name":"Delhi", "id":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd", "Towns":[ ...

JavaScript validation function stopping after the first successful validation

Script: NewsletterValidation.js function formValidation() { var fname = document.getElementById('firstName').value; var lname = document.getElementById('lastName').value; var pnumber = document.getElementById('phoneNumb ...

Struggling to adjust the quantity of items in a basic shopping cart when adding multiples of the same item

Hello there! I'm currently working on a project where I need to increase the quantity of each item added to the cart if it's already in there. This is actually my first time posting, so any tips on asking better questions would be greatly appreci ...

The video continues playing even after closing the modal box

I am facing an issue with my code where a video continues to play in the background even after I close the modal. Here is the code snippet: <div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria- ...

NPM is searching for the package.json file within the user's directory

After completing my test suite, I encountered warnings when adding the test file to the npm scripts in the local package.json. The issue was that the package.json could not be located in the user directory. npm ERR! path C:\Users\chris\pack ...

Vue.js Interval Functionality Malfunctioning

I'm brand new to Vuejs and I'm attempting to set an interval for a function, but unfortunately it's not working as expected. Instead, I am encountering the following error: Uncaught TypeError: Cannot read property 'unshift' of u ...

Retrieve a specific subset of keys from a JSON column

I am working with a table column that looks like this: The goal is to extract the trailing numbers from the key names and organize them as shown below: ID 1 2 3 4 Currently, I am able to retrieve it using the following code: REGEXP_REPLACE(( ...

Rapidly process likes from all Facebook friends by making multiple JSON requests

I had an interesting idea to develop a program that could analyze the likes of a person's Facebook friends. While there are likely other applications out there claiming to find your "Perfect Match" based on this data, I wanted to create something uniq ...

Switch off any other currently open divs

I'm currently exploring a way to automatically close other div's when I expand one. Check out my code snippet below: $( document ).ready(function() { $( ".faq-question" ).click(function() { $(this).toggleClass('open'); $(this ...

Challenges encountered when passing objects with Angular 2 promises

I am encountering a problem when using a promise to retrieve a Degree object in Angular 2. The initial return statement (not commented out) in degree.service functions correctly when paired with the uncommented implementation of getDegree() in build.compon ...

Ways to eliminate the top space in the background image

After implementing a basic HTML code to add a background image to my webpage, I noticed there is still some empty space at the top of the page. I attempted to adjust the position of the background image using the following code, but it only lifted it upwar ...

Executing `console.log()` in Windows 8 using JavaScript/Visual Studio 2012

Whenever I utilize console.log("Outputting some text") in JavaScript within Visual Studio 2012 for Windows 8 metro development, where exactly is the text being directed to? Which location should I look at to see it displayed? Despite having the "Output" pa ...

Creating a node.js function that can be used with OracleDB

I'm currently delving into learning nodeJS, but I'm facing a roadblock and can't seem to figure out what's causing the issue. Even the Debugger isn't providing much help. Any assistance or guidance would be greatly appreciated. The ...