JS/Apps Script: Passing object and its keys as function parameters

When working with Google Apps Script, I have a specific task that involves looping through data and writing only certain keys to a sheet. I want this looping operation to be done in a separate function rather than directly in the main function, as it will be used multiple times.

How can I modify the print_data() function to achieve the same output as it does within the main() function?

function main() {

  const data = [{"key_1":10,"key_2":20,"key_3":30},{"key_1":40,"key_2":50,"key_3":60}];

  // Print data
  for (let i=0; i<data.length; i++) {
    const d = data[i];
    Logger.log([[d.key_1,d.key_3]]);
  }

  const keys = [[d.key_1, d.key_2]];
  print_data(data, keys);

}

function print_data(data, keys) {

  for (let i=0; i<data.length; i++) {
    const d = data[i];
    Logger.log(keys);
  }

}

Solution:

function test_main() {

  const data = [{"key_1":10,"key_2":20,"key_3":30},{"key_1":40,"key_2":50,"key_3":60}];
  const keys = ["key_1","key_3"];

  // print_data(data, keys);
  print(data, keys);

}

function print(data, keys) {

  ss = SpreadsheetApp.getActiveSpreadsheet();
  sheet = ss.getSheetByName("Test");
  sheet.clear();

  for (let i=0; i<data.length; i++) {
    arr = Array(keys.map(k => data[i][k]));
    sheet.getRange(i+1,1,1,2).setValues(arr);
  }
}

Answer №1

If you provide the keys as strings, you can then utilize Array#map to extract the corresponding values for those keys from the current object.

const Output = console; // example usage
function main() {
  const collection = [{"key_1":10,"key_2":20,"key_3":30},{"key_1":40,"key_2":50,"key_3":60}];
  const keyNames = ['key_1', 'key_3'];
  display_data(collection, keyNames);
}
function display_data(collection, keyNames) {
  for (let i = 0; i < collection.length; i++) {
    Output.log(keyNames.map(k => collection[i][k]));
  }
}
main();

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

MUI: Autocomplete received an invalid value. None of the options correspond to the value of `0`

Currently, I am utilizing the MUI autocomplete feature in conjunction with react-hook-form. I have meticulously followed the guidance provided in this insightful response. ControlledAutoComplete.jsx import { Autocomplete, TextField } from "@mui/mater ...

Reactjs may have an undefined value for Object

I have already searched for the solution to this question on stackoverflow, but I am still confused. I tried using the same answer they provided but I am still getting an error. Can someone please help me resolve this issue? Thank you. const typeValue = [ ...

reversed json using javascript

Is it possible to efficiently reverse the order of the following JSON object: { "10": "..." "11": "...", "12": "...", "13": "...", "14": "...", } so that it becomes: { "14": "...", "13": "...", "12": "...", "11": "... ...

Unable to utilize the 'require' function in subdirectories within the node_modules directory

In the development of my express api, I have set up routes as a dependency within the main project. The main project contains a config folder with an index.js file that exports an object serving as the route configuration. While I can access this exported ...

Selenium, scrolling through web pages

I have been attempting to scroll through a webpage using Selenium at "https://jobsearch.az/vacancies". However, when you open the page and click on a job vacancy, there are two side-by-side pages that need to be scrolled. The challenge is to scroll the one ...

Creating an AI adversary for a simple Tic Tac Toe game board: a step-by-step guide

Being new to programming, I recently completed a basic Tic Tac Toe gameboard successfully. However, as I progress to the next phase of my assignment which involves implementing an AI opponent, I encountered several challenges. As a novice in programming, ...

Do not decode HTML content within an iframe; instead, extract the data directly from the HTML source

To expedite execution time, we have made the decision to not display the table in the iframe as it is invisible to the client. However, we still need to update the main page table by copying its contents. The approach we are taking is that the iframe shou ...

Type of variable that is not an array

I need a quick way to check if a value is an object {} but not an array []. The code I currently have is: function isPlainObject(input) { return !Array.isArray(input) && typeof input === 'object'; } Is there a more concise method to a ...

"Error: The angularjs code is unable to access the $http variable within

$http({ url: "php/load.php", method: "GET", params: {'userId':userId} }).success(function(data, status, headers, config) { $scope.mydata = data; mydata = data; }).error(function(data, status, headers, config) { }); It's puzzling why ...

Schedule Master: A sophisticated tool for time management

I have been following the instructions to implement a date time picker from this tutorial. I downloaded the necessary js and css files and placed them in the respective directories. However, when I click on the calendar icon, the calendar does not pop up. ...

Mongoose: Enhancing Arrays with maximum values for each item

How to Update an Array Property in Mongoose with Item-Wise Max and Default Null Upon Instantiation I have a MongoDB collection that stores time series data in a fixed-length array (1 item per minute, 1 document per day). { 'series': '#1& ...

How can you nest a map within a map in JavaScript?

Here is the code snippet I am working with: _renderChannels() { return this.state.channelsData.map(channelData => { return this.state.channelsStreamData.map(channelStreamData => { return <Channel channelData={channelData} ch ...

The styling of the CSS is tailored to various breakpoints

source: Display helpers How can I dynamically change CSS styles based on the current breakpoint size? For example, can I set different sizes, positions, and colors for elements when the window is on xs compared to md or other breakpoints? ...

How can I effectively send a form with the value of 'put' using Laravel and Ajax?

I have been working on a function that utilizes AJAX to validate and send responses to the view when an edit form is submitted. However, I am encountering an issue where the page loads on a new URL like localhost:8000/comment/id, and I want the page to dis ...

Troubleshooting unexpected issues with dynamically updating HTML using innerHTML

Need help with a renderWorkoutUpdated function that replaces specific workout records with updated values. _renderWorkoutUpdated(currentWorkout) { let html = `<li class="workout workout--${currentWorkout.type}" data-id="${ curre ...

Inserting an HTML element into Handlebars.js during a specific iteration of an each loop

I have a channel.json file containing 7 objects of data which are iterated in hb. I am looking for a way to insert a date between these iterations without modifying the .json file. How can I add an html tag to display after the 3rd iteration within the loo ...

V-Calendar is not displaying the accurate dates

https://i.stack.imgur.com/zk4h7.png The image displays dates starting on June 1, 2022, which should be a Wednesday but appears as a Sunday on the calendar. This issue affects all months as they start on a Sunday instead of their respective weekdays. The p ...

Trigger Javascript on 'Nearby' input from Html form

I have a JavaScript code that retrieves the latitude and longitude of users from their device for a local search. Although everything works correctly, I want to make sure the script is only executed if the user specifically selects "nearby" as the locatio ...

Changing the colors of multiple buttons in a React Redux form: a step-by-step guide

When using Redux Form Wizard on the second page, I have two buttons that ask for the user's gender - Male or Female. The goal is to make it so that when a user clicks on either button, only that specific button will turn orange from black text. You ...

Manipulate a deeply nested JSON object in JavaScript by iterating through it and constructing a new data

Struggling to rearrange complex JSON data (data1) into a more organized format (data2). Progress has been slow. data1 is created by scanning a parent directory (recipes) for html files. data2 is the desired output structure using data1, where content wit ...