Implementing Google APIs with Next.js: Managing arrays without keys

Recently, I've started using next.js and came across the getStaticProps function. In this function, I'm loading data from a Google Sheet table into a constant. The result is an array of arrays, just like what the Google API returns shown below:

[ [ "CLIENT A", "MIKE", "UNKNOWN", "TRADICIONAL" ], [ "CLIENT B", "MARY", "UNKNOWN", "MOROSO" ], [ "CLIENT C", "MIKE", "CLIENT C S.A DE C.V.", "TRADICIONAL" ], [ "CLIENT D", "JOHN", "RAZON SOCIAL CLIENT", "TRADICIONAL" ] ] 

I am passing this array as props but struggling to manipulate the information in order to display it in the desired format:

CLIENT A
Salesperson: MIKE
Razón Social: UNKNOWN
Category: TRADICIONAL

--------------------

CLIENT B
Salesperson: MARY
Razón Social: UNKNOWN
Category: MOROSO

--------------------

CLIENT C
Salesperson: MIKE
Razón Social: CLIENT C S.A DE C.V.
Category: TRADICIONAL

I have been trying to figure out a way to add keys to the array, such as:

{ client: "CLIENT A", salesperson: "MIKE", razonsocial: "UNKNOWN", category: "TRADICIONAL", } 

I also attempted to map the array of arrays but encountered an error stating that mapping was not possible.

If anyone could provide guidance on the best approach to handling this array, I would greatly appreciate it!

Answer №1

Does this suit your needs?

let details = [
  ["CUSTOMER A", "MIKE", "UNKNOWN", "TRADITIONAL"],
  ["CUSTOMER B", "MARY", "UNKNOWN", "OVERDUE"],
  ["CUSTOMER C", "MIKE", "CUSTOMER C S.A DE C.V.", "TRADITIONAL"],
  ["CUSTOMER D", "JOHN", "COMPANY NAME CUSTOMER", "TRADITIONAL"]
];
const headings = ['', 'Salesperson', 'Company Name', 'Category'];
details.map(detail => {
  detail.forEach((element, index) => {
    console.log(`${headings[index]?headings[index]+": ":''}${element}`)
  })
  console.log('------------------');
})

Answer №2

Essentially, my goal is to pass the data array as props to my default function. The issue lies in my inability to map the renglon object and assign keys to it. In the function home, the client.name property is not functioning due to the key creation constraint and I am unable to access properties using client[0].

import { google } from 'googleapis';

export async function getStaticProps() {
  
    const auth = await google.auth.getClient({ scopes: ['https://www.googleapis.com/auth/spreadsheets.readonly'] });

    const sheets = google.sheets({ version: 'v4', auth });
    const range = `Sheet!A$2:D`;

    const response = await sheets.spreadsheets.values.get({
        spreadsheetId: process.env.SHEET_ID,
        range,
    });

    // The challenge of adding keys to renglon persists
    const renglon = response.data.values;
    
    if (renglon.length) {
      return {
        props: {
          renglon,
        }
      };
    }

}

export default function Home( { renglon } ) {
    return (
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {renglon.map((client) => {
         return (
            <li>Client: {client.name}</li>  //Unable to create this key or access using client[0]
            Sales person: {client.salesperson}<br />//Unable to create this key or access using client[1]
            Razón Social: {client.razonsocial}<br />//Unable to create this key or access using client[2]
            Category: {client.category}<br /> //Unable to create this key or access using client[3]
         )
       })}
      </div>
    );
}

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

The Use of Arrays and Rvalues as Function Parameters

Curiosity strikes as I ponder the possibility of distinguishing function calls (with arrays as parameters) in the code snippet below: #include <cstring> #include <iostream> template <size_t Size> void differentiate_arrays( const char (& ...

What is the best way to retrieve distinct id values from a form in Rails when sending a DELETE request via AJAX?

I am determined to grasp the intricacies of AJAX and how it operates, hence, I prefer not to use "remote: true" for this task. The issue at hand is that despite attempting to send a DELETE request to the server using a form input, each submission results i ...

In search of assistance with accessing API data from an object, not an array, in React

Hi there! I'm encountering a problem while trying to fetch an API in my app. I'm attempting to retrieve information from a JSON object, but keep running into the error "this.state.data.map is not a function." I understand that map is meant for ar ...

How to target a class in jQuery that contains two specific strings

There are multiple images in my HTML, each assigned two classes. Here's a snippet of the relevant code: class = "thing other0-a" class = "thing other1-a" class = "thing other2-a" class = "thing other3-a" class = ...

Activating/Deactivating the Submit Button with jQuery and Bootstrap

Some of my form fields are outside of the <form> tag. I want the form to be disabled on load, and only enable once users input data into multiple fields. I'm facing two issues. Firstly, the jQuery code I have only works for one field at a time. ...

Sending a Form Generated in Real Time with a Button Located Outside the Form

I'm currently working on a feature that allows users to add multiple invoices on a single page. Users can click on a link to display the invoice fields in a modal form, which is dynamically generated using AJAX. Once the user has filled out the requi ...

Converting a list of data into a two-dimensional array for easy processing

After reading a file into a C# console app, I have a dataset that includes player information like this: Player;Team;POS;HR;RBI;AVG Abreu, J;CWS;1B;30;101;0.29 Altuve, J;HOU;2B;15;66;0.313 Andrus, E;TEX;SS;7;62;0.258 Now, I need to sort all 143 ite ...

Guide on separating a variable by commas using jQuery

After making an Ajax call to a Java servlet, I am retrieving data and storing it in the 'data' variable upon success. Here is the code snippet: var s1=""; var ticks =""; $('#view').click(function(evt ...

Why do class definitions become unavailable in Javascript due to the semantics of `require()`?

I am encountering an issue with file allocation.js which contains the definition of class Allocation {...}. In another file called test.js, I have included require('./allocation.js'), followed by a = new Allocation;, which results in a ReferenceE ...

What is the reason for Jquery AJAX appending additional path to the relative path?

I am encountering an issue with the following code snippet $.ajax({ url: "search/prefetch", success: function (data) { $(".result").html(data); alert("Load was performed."); }, dataType: "json" } ...

Protecting client-side game logic operations with web application security

I've been developing a web-based game that utilizes the Canvas feature of HTML5. However, I've come to realize that there is a significant vulnerability in my system. The scoring and gameplay statistics are currently being calculated on the clien ...

Replace the current CSS styles of a pre-installed package

I recently added a package for a type writer effect, but I'm having trouble with it not overriding the CSS styles I've set in the component. Here's an example of what I have: <template> <v-row class="hero" align-content= ...

The Workbench has "Rejected the setting of an insecure header 'content-length'"

While working on implementing a simple xhr abstraction, I encountered a warning when trying to set the headers for a POST request. Strangely, I noticed that the issue might be related to setting the headers in a separate JavaScript file. This is because wh ...

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 ...

Is it possible to update the CSS file of an external SVG file in real-time?

Is there a way for an SVG image to reference another CSS file? A webpage contains an SVG file. A button allows users to switch between classic colors and high contrast mode on the entire webpage, including the SVG image. Attempt w.css (white backgrou ...

The modal window obstructs my view on the screen

You are working with a modal form that triggers a POST method in your controller https://i.sstatic.net/0vbOy.png Here is the view code: <div class="modal fade" id="agregarProducto"> <div class="modal-dialog" role="document"> < ...

The JSON parser is still encountering issues with newlines, despite attempting to fix the problem by adding

I'm currently working on a messaging platform for a school project and facing challenges in ensuring database protection, defending against XSS attacks, and accommodating all characters, including newlines. Everything seems to be in place, except for ...

Encountering challenges with implementing debouncing functionality in React programming

import React,{useState} from 'react'; const app = () => { const [inputValue, setInputValue] = useState(); const handleChange = (e) => { setInputValue(e.target.value); console.log(inputValue); } const d ...

How can I toggle the radio button based on the dropdown selection?

I'm attempting to enable or disable a radio button based on the selection from a dropdown menu. View my jsfiddle example here For example, if the user selects "persons" from the dropdown, only the options for Anthony and Paul should be available to ...

What is the most efficient way to update a large batch of documents in MongoDB?

I need to efficiently update a large number of documents (> 100,000). Initially, I attempted to do this on the JS level by writing scripts that fetch _ids first and then loop through them to invoke updates by _id (full docs or $set patches). However, ...