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

Exploring the integration of Formik with Material-UI's select field - A step-by

Trying to implement Formik with Material-UI's Textfield component using the select attribute. Every time I change the option, it shows this warning: Material-UI: You have provided an out-of-range value null for the select (name="subIndicatorId& ...

Retrieve a subsection of an object array based on a specified condition

How can I extract names from this dataset where the status is marked as completed? I have retrieved this information from an API and I need to store the names in a state specifically for those with a completed status. "data": [ { "st ...

Storing JSON information in the database at a specified moment

I am interested in truncating and storing JSON data from an external URL daily at a specific time, which is 10pm. The URL requires login credentials, which I possess, but I am unsure of the best approach to take. The structure of the JSON data is as follo ...

Applying binary information to an image

Let's say I have an <img/>. The img is initially set with src='http://somelocation/getmypic'. Later on, there might be a need to change the content of the image based on some ajax call that returns binary data. However, this decision c ...

What is the best method for utilizing a single L.Shapefile/zip file Object and modifying the onEachFeature function for each layer?

I am currently facing an issue where I have multiple tileLayers each containing a shape file. These tile layers represent different datasets based on variables and adjust colors accordingly. I have been able to achieve this by creating three separate Obje ...

Is it possible to utilize Faker for generating fabricated JSON data?

Is there a method to generate fictitious data, like a name and email, and save it in a JSON file? I'm aware that faker is utilized with Node and NPM for creating fake data in JS, but can the same be done with JSON? ...

Angular: NaNa: Attempting to access a property of an undefined variable

I've encountered these errors although the values are displayed correctly in the browser. I'm unsure about how to resolve this issue. ERROR TypeError: Cannot read property 'length' of undefined ERROR TypeError: Cannot read property &ap ...

Implementing restify on a website that mandates user login authentication

Currently, I am operating a REST API server using restify. In addition, my front-end consists of angularjs with html, css, and js files hosted on an Apache webserver. The next step is to implement user login authentication for this webapp. Access to the w ...

Storing values as JSON in Redis: A comprehensive guide

In my application, I have implemented Redis as the caching store. Below is the configuration setup for Redis: @Configuration @EnableCaching public class SpringRedisConfig { @Bean public JedisConnectionFactory connectionFactory() { JedisConnectionFacto ...

Unraveling nested elements with the array map() method in Angular2 and Typescript: Fixing the issue of undefined property reference while mapping

Hey there! I'm currently working with Angular 4 and I have a piece of code that parses data from an API into a TypeScript array of rows. It's important to note that the code functions properly if elements like 'item.tceCampRun' and &apo ...

Display only one dropdown menu at a time

Hey there, I'm currently working on a dropdown menu and struggling to figure out how to keep only one item open at a time. I've tried using an array with useState for all my dropdowns but haven't been able to find a solution yet: code co ...

Encountering the "Variable is not defined" error even when the variable has been previously defined. Currently working with EJS and Node

38| <h2 class="card-activity"> 39| <!-- Display Activity --> >> 40| <%= data.activity %> 41| </h2> 42| <div class="card-info"> 43| ...

Information sent to a slot does not trigger a response

Trying to create a mobile-friendly chat app, I want to hide the new message button during conversations and use a different button on desktop. In addition, I have a dialog for creating new chat groups. <v-dialog transition="dialog-top-transition&qu ...

Issue with Gijgo grid not updating properly during change event

I'm currently working on an MVC 5 application and I've hit a roadblock with a particular view. This view contains a dropdown menu and a grid (Gijgo-grid). The grid's content is supposed to change based on the selected value from the dropdown ...

Employ the Google Charting library for creating a GeoChart that is currently not displaying

Hello everyone. I'm having a bit of an issue with my web page development. I've been trying to add a GeoChart, but no matter how many times I copy-paste the code from the Google developer's website, the map just won't show up. I must be ...

The close button within the modal is malfunctioning even with the implementation of the on() function

My "show more" button triggers the modal to pop up, but when I click on the X button in the top left corner, it doesn't close as expected. However, clicking outside of the box or pressing the "esc" key does work. I suspect that the issue lies with th ...

A server that broadcasts using Javascript, Node.js, and Socket.IO

Could someone provide a simple example of how to create a Node.JS server that runs both a TCP and Socket.IO server? The main goal is to pass data from a TCP client to multiple Socket.IO clients who are interested in it. This setup is intended to facilita ...

Is it possible to utilize "this" in mapMutations spread within Vue instance methods?

Trying to define Vuex mutations like this: export default { props: { store: String }, methods: { ...mapMutations({ changeModel: `${this.store}/changeModel` }) } } Encountering an error message: An er ...

Passing form data to PHP using AJAX in CodeIgniter Framework

I'm facing an issue with my HTML structure which is as follows: <form method="POST"> Name : <input id="asgname" type="text"> <br> Description : <input id="asgdescription" type="text"> <br> <a href="#" id=" ...

Reviewing user input for any inappropriate characters using jQuery's functionality

When a username is inputted into the input box, I want to make sure that only valid characters are accepted. The following code shows what I have so far; but what should I replace "SOMETHING" with in the regular expression? var numbers = new RegExp( ...