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

Switching between multiple images using Jquery on a click event

Hi there, I am currently working on a project where I need to use jQuery to switch between three images when clicked. Once the third image is clicked, it should cycle back to the first picture. I was wondering if there is a way to modify the code below so ...

useEffect runs endlessly

Currently, I am using React with hooks to handle API calls and implement autoscroll functionality on a data-heavy screen. However, I have encountered a problem where the autoscroll feature implemented through a separate useEffect is interfering with the ot ...

Retrieve JSON Object using a string identifier

I created a script that takes the ID of a link as the name of a JSON dataset. $('.link').click(function() { var dataset = $(this).attr("id"); for (var i = 0; i < chart.series.length; i++) { chart.series[i].setData(lata.dataset ...

Response with a JSON arraylist is returned

I am relatively new to JSON and jQuery, and I am trying to retrieve JSON data using AJAX. My goal is to display this data upon clicking a submit button. Here is the code snippet that I attempted: PrintWriter out = response.getWriter(); List<Countries&g ...

Uh oh! There seems to be an issue with the ClerkJS frontendAPI option. Visit the homepage at https://dashboard.clerk.dev to retrieve your unique Frontend API value

Despite inputting the correct Clerk API keys, I'm encountering issues with the functionality of the ClerkJS API. I anticipate that the application should enable me to utilize the ClerkJS API for user authentication without any problems. ...

Inquiry into the use of Jquery.ajax()

Hey there, I'm curious about using Jquery Ajax to retrieve a numeric value from a website. Any suggestions on where I should begin? Any advice would be greatly appreciated. Thanks in advance! Best regards, SWIFT ...

Displaying the URL of a link on the screen using jQuery

I am looking for a solution to add a link address after the link itself in a table containing reference links for our staff. I have used CSS to achieve this in the past, but the address was not copyable by users. Instead, I am interested in using jQuery&ap ...

The combination of Array.pop and Array.indexOf is not functioning as expected

I'm having an issue with using Array.pop(Array.indexOf(value)). It seems to always delete the last element in the index, even if the value of that index is not what I intended. Can someone provide some guidance on how to resolve this? CheckBoxHandle ...

Is it advisable to compress my API response in PHP?

At this stage, I find myself needing to generate extensive reports in order to gain a better understanding of the data at hand. To do so, I must retrieve one of my tables which contains around 50 parameters and 40,000 rows. While fetching the data via API ...

Is there a way to identify the top five elements that are most frequently occurring in the array?

I've successfully found the element that appears the most in an array, but now I'm facing a new challenge where I need to identify the top 5 elements that appear most frequently. Here is the array: [ "fuji", "acros", &q ...

What is the process for filtering by condition on a JSON column in MySQL?

What is the best way to construct a query for selecting data based on a where condition from a column containing a JSON array? For example, let's say I have a table called ci_sessions with columns user_name, user_role, and user_data which is stored as ...

Calculating the position of an element in an array passed from a separate file with ReactJS and Ant Design

I'm currently working with a file that contains some JavaScript code featuring an array with multiple objects containing key-value pairs. In my main file (App.jsx), I initialize a State Variable and assign it the array from another JS file. My goal no ...

JavaScript form not working on submission

When my form is submitted, a function is called that successfully redirects users on desktop to either the download-confirmation or download-failure page. However, when testing on mobile devices such as iOS and iPad, the redirection does not seem to work. ...

Is it possible to modify the HTML/CSS of a child component using the parent component in Angular 2+?

Is there a way to dynamically add text and style to a specific row in a child component based on the parent's logic? (parent): <body> <child-component></child-component> </body> (child): <div *ngfor = "let record in r ...

Combining two kebab-case CSS classes within a React component

import React from 'react'; import styles from './stylesheet.moudle.css' <div className={styles['first-style']} {styles['second-style']}> some content </div> What is the correct way to include styles[&ap ...

The React Functional Component undergoes exponential re-renders when there is a change in the array

I'm encountering a problem with one of my functional components. Essentially, it maintains an array of messages in the state; when a new message is received from the server, the state should update by adding that new message to the array. The issue ar ...

Implementing Android Volley framework

Hey folks, I could really use some assistance! I'm a beginner with Volley and have been tackling login and registration using it. Specifically, I'm struggling with inserting and retrieving data in the database using JSON arrays and objects. Below ...

Adding an image to a server through PHP in the TinyMCE editor

Currently, I am in the process of utilizing TinyMCE text editor for uploading images using PHP and JS database. However, I find myself perplexed when it comes to sending the image to the server. Below is the snippet of the JS code being used: <script ...

What is the best way to isolate a single element within a for loop and exclude all others?

I have implemented a dynamic Ajax call to compare the string entered in the text field (representing a city name) with the "type" value in a JSON array. As I iterate through the elements of the array, I am checking the values associated with the key "type ...

Loading data dynamically in a table by utilizing the react WayPoint library

I'm currently utilizing a combination of material UI table and react-table. When the number of rows in the table exceeds around 200, the performance dips. To address this issue, I am looking to display a fixed number of rows (let's say 20 rows) i ...