What is the best way to retrieve JSON key/value pairs instead of an array?

I am working on retrieving data from a Google Spreadsheet using App Script and have set up a DoGet function. Currently, I am getting an array of data but I need it in JSON key-value pairs format.

The table in my Google Sheets is structured as follows:

This is how the DoGet function is currently configured:


function doGet(e) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); 

  var returnData = sheet.getRange('A1:B2').getValues()

return ContentService.createTextOutput(JSON.stringify(returnData))
}

The current output looks like this:

[
    ["fruit", "vegetable"],
    ["ABC", "DEF"]
]

However, I actually need the data to be in JSON key:value pairs like this:

{
"fruit": "ABC",
"vegetable": "DEF"
}

Answer №1

Make use of the Array:slice and Array:map functions to achieve your desired result.

Check out the code snippet below :

const nestedArray = [
  ["apple", "banana"],
  ["123", "456"],
  ["XYZ", "PQR"],
  ["AA", "BB"],
  ["CC2", "D3D"]
];

function transformArr(arr) {
  let modifiedArray = arr.slice(1).map(subArray => {
    let newObj = {};
    if (subArray.length >= 2) {
      newObj[arr[0][0]] = subArray[0];
      newObj[arr[0][1]] = subArray[1];
    }
    return newObj;
  });

  return modifiedArray;
}

console.log(JSON.stringify(transformArr(nestedArray)));

Answer №2

One issue you may encounter is when extracting a value from a Google Sheet, causing your data to be shown in this particular format.

[
    ["fruit", "vegetable"],
    ["ABC", "DEF"]
]

To obtain the desired response, you need to appropriately map your data.

const arrayData = [
    ["fruit", "vegetable"],
    ["ABC", "DEF"]
];

const resultObject = arrayData[0].reduce((acc, key, index) => {
    acc[key] = arrayData[1][index];
    return acc;
}, {});

console.log(resultObject);

However, a challenge arises if there are more rows - how would you manage the situation then?

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

Exploring the secure synergy between Laravel 5.5 Passport client_secret and Vue JS authentication

Greetings to all, Currently, I am delving into the world of Laravel Passport and Vue.JS (standalone) simultaneously. In my authentication process, I am utilizing the Password Grant Token. An issue that has come up is the necessity for keeping the secret_ ...

Understanding the difference between Parameters in Javascript and Java

Currently, I am facing an issue where I am losing some information while sending an ajax request to a servlet. The specific parameter that I am losing data from is the "comment" parameter. Below are the last 4 lines of my ajax code: var params = "name=" + ...

Having trouble with your Bootstrap 4 Dropdown Menu?

I attempted to implement the dropdown menu example from Bootstrap 4, but unfortunately it does not seem to be working as expected. The dropdown menu does not appear when clicked. <li class="nav-item dropdown"> <a class="nav-link dropdown-to ...

Error: The component passed is invalid and cannot be defined within kendo UI

Check out this example https://www.telerik.com/kendo-vue-ui/components/grid/ showcasing a computed method gridSearchMessage() { return provideLocalizationService(this).toLanguageString( "gridSearch", "Search in all colu ...

Creating a reusable field for reactive forms in Angular: A step-by-step guide

I need assistance with creating a versatile field component for reactive forms, but I am facing challenges in retrieving the value from the custom-input element. <form [formGroup]="form" (ngSubmit)="submit()"> <custom-input i ...

The novice image slideshow script in JavaScript is causing all images to disappear and generating errors

Trying to create a simple image slider that pulls information from various sources. CSS and HTML are set up properly, but adding the JavaScript logic causes all images to disappear. The console displays an error saying "Uncaught TypeError: Cannot read prop ...

Tips for saving data obtained from an ajax call

My jquery ajax function has a callback that creates an array from retrieved json data. Here's an example: success: function (response) { callback(response); }, The callback function, in this case createQuestionsArray(), populates ...

What is the best way to distinguish between inline javascript and dynamically created content in Express/Node.js?

I've encountered a bit of a noob-question despite having a few years of experience in web development. Despite searching Programmer Stack Exchange and Google, I haven't found an answer, so here goes. Currently, I'm working with the Express ...

Fixing a scrolling element within a div located below the screen is my goal, ensuring it remains fixed in place as the user scrolls

I'm facing a challenge that I need help with: My HTML/CSS layout currently looks like this: Screenshot of how my CSS/HTML appears on the screen upon page load: As I scroll down, I encounter a green element: While scrolling down -> Upon further s ...

The absence of the Django CSRF token has been detected

Inside the custom.js file, there is a function defined as shown below : function contactTraxio(fullname, telephone, email) { if (typeof(fullname)==='undefined') fullname = null; if (typeof(telephone)==='undefined') telephone = ...

Exploring how to compare time in hh:mm format using JavaScript

After switching to 24-hour format for my strings, I'm confused as to why the times are not comparing correctly. What am I doing incorrectly? function convertToTwentyFourHourTime(amPmString) { var d = new Date("1/1/2013 " + amPmString); ...

The message "In Angular, there is no such property as 'data' in the type '{ user: User; session: Session; error: ApiError; }'."

Here is my complete supabase.service.ts code: import { Injectable } from "@angular/core"; import { createClient, SupabaseClient, User } from "@supabase/supabase-js"; import { BehaviorSubject } from "rxjs"; import { envi ...

What is the best way to handle an AJAX request within an if-else statement?

Attempting to utilize an if-else condition in order to make a jQuery Ajax call to an API. Having trouble understanding why the ajax function is being called even though it should be in the else statement. Below is the code snippet: if (e.value == null | ...

Keep things in line with async functions in Node JS

Hello, I am just starting out with NodeJs and I have a question. I am trying to push elements into an array called files based on the order of the urls provided, but it seems like I'm getting a random order instead. Below is the code I've been wo ...

retrieving key and value quickly using rapidjson

I am currently attempting to retrieve both the key and value of an object within an array, but I am struggling to find the appropriate getter method: for (Value::ConstValueIterator itr = document["params"].Begin(); itr != document["params"].End(); ++itr) ...

Iterate through JSON objects within Ansible

Struggling to extract a specific JSON object based on the value of a key matching a string variable. Here is a snippet of the JSON file: "totalRecordsWithoutPaging": 1234, "jobs": [ { "jobSummary": { "totalNum ...

Is there a way to stop a music track from playing?

function playMusic(){ var music = new Audio('musicfile.mp3'); if (music.paused) { music.play(); } else { music.pause(); } } <input type="button" value="sound" onclick="playMusic()" ...

The configuration of the Braintree API client is incorrect: the clientApiUrl found in the clientToken is not valid

Error Found: Braintree API Client Misconfiguration - The clientApiUrl provided in the clientToken is invalid. Upon checking my browser log, I noticed this error. I am using a Node backend with an Angular front end and integrating Braintree javascript SDK ...

How can I convert an xlsx file to JSON using ExcelJS in Node.js?

https://github.com/guyonroche/exceljs I am a beginner with exceljs and just came across the description of exceljs on github. The description states: "Read, manipulate and write spreadsheet data and styles to XLSX and JSON." I am looking for a way to ...

Transferring PHP session variables from jQuery and Ajax to the PHP gratitude page

I've been mulling over this puzzle for quite some time now. My approach involves utilizing jQuery AJAX POST method to transmit form data using session variables from home.php to thankyou.php. Subsequently, the user is redirected (window.location.href ...