Problems with Arrays in Google Apps Script

I'm currently developing an apps script that loads XML data into a function and parses it based on user input.

The XML structure is fairly simple:

<?xml version="1.0" encoding="UTF-8"?>
<Records>
    <Record>
        <username>jjohnson</username>
        <firstName>John</firstName>
        <lastName>johnson</lastName>
        <email><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="33595c5b59">[email protected]</a></email>
    </Record>
    <Record>
        <username>bsimmons</username>
        <firstName>ben</firstName>
        <lastName>simmons</lastName>
        <email><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb898e85868e8786838197">[email protected]</a></email>
    </Record>
    ...etc
</Records>

The function reads the XML, converts the data to an object array, filters by username, and displays matching rows in Google Sheets.

function XMLCONTACT(username) {
var url = '<XML source>';
var ContactXml = UrlFetchApp.fetch(url).getContentText();
var document = XmlService.parse(ContactXml);
var root = document.getRootElement();
var arr = [];
var XMLChildren = root.getChildren("Record");

for (var i = 0; i < XMLChildren.length; i++) {    
    arr.push({ 
        username: XMLChildren[i].getChild("username").getText(),
        firstName: XMLChildren[i].getChild("firstName").getText(),
        lastName: XMLChildren[i].getChild("lastName").getText(),
        email: XMLChildren[i].getChild("email").getText()
   });
}

var newarr = []

for(var j= 0; j < arr.length; j++){
  if(arr[j].username === username ){
        newarr.push(arr[j]);
  }
}
    return newarr;
}

However, I'm facing an issue where the function doesn't return any output. While I can display the array content without objects, the filtered results are not showing up. Any assistance would be greatly appreciated!

Thank you for your support!

Answer №1

If you are looking to transfer the results of the function XMLCONTACT() into a Spreadsheet, consider making some adjustments to your script. It seems like you want to utilize XMLCONTACT() as a custom function for your Spreadsheet. To achieve this, you can modify your code as shown below:

The function should return values in a 2-dimensional array format.

Original Code :

var newarr = []
for(var j= 0; j < arr.length; j++){
  if(arr[j].username === username ){
    newarr.push(arr[j]);
  }
}
return newarr;

Modified Code :

var newarr = [];
for(var j= 0; j < arr.length; j++){
  if(arr[j].username === username ){
    newarr.push([arr[j].username, arr[j].firstName, arr[j].lastName, arr[j].email]);
  }
}
return newarr;

Important Notes :

  • This script assumes it is bound to the Spreadsheet container.
  • To use the modified script, enter =XMLCONTACT2("jjohnson") into a cell on your spreadsheet.
  • If you need to rearrange the values, edit the line
    newarr.push([arr[j].username, arr[j].firstName, arr[j].lastName, arr[j].email]);
    . Feel free to reach out if you require further clarification.

If my interpretation differs from your intention, please inform me so I can adjust my response accordingly.

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

Optimizing Angular for search engines: step-by-step guide

Regarding Angular SEO, I have a question about setting meta tags in the constructors of .ts files. I have implemented the following code: //To set the page title this.titleServ.setTitle("PAGE TITLE") //To set the meta description this.meta.addTag ...

The Fusion of JavaScript Frameworks

Is it considered poor practice for a seasoned developer to build a web application using multiple JS frameworks? For instance, when incorporating AngularJS into a project, and certain tasks could be more efficiently achieved with JQuery, should one opt fo ...

Show XML content in HTML text box

How can I process and display an XML file in a text area without any special formatting? I am exploring different solutions for this task. <?xml version="1.0"?> <phonebooks> <contacts group_name="Sample" editable="1" id="0"> <contact ...

ChartJS is exhibiting an issue within a modal or popup window where the chart is being displayed with a height

I want to show a graph in a modal window when the user clicks a button. The modal is hidden with display: none;, and becomes visible with display: flex; once the button is clicked. If I move the chart outside of the modal, it works without any issues. Ad ...

Is there a way to prevent webpack from replacing process.env variables with their values during the build process?

Within one of my project files, I have the following snippet: const identifier = process.env.DBID; console.log('identifier', identifier); When I execute the command: cross-env PORT=4000 NODE_ENV=production WEBPACK_CONFIG=browser_prod,server_p ...

Steps to remove a row from a table in a ReactJS component

I'm struggling with implementing a delete operation for table rows and encountering errors. Any assistance in resolving this issue would be greatly appreciated. Since I am unsure how to set an auto-incrementing id, I used Date.now(). Now my goal is t ...

Another component's Angular event emitter is causing confusion with that of a different component

INTRODUCTION In my project, I have created two components: image-input-single and a test container. The image-input-single component is a "dumb" component that simplifies the process of selecting an image, compressing it, and retrieving its URL. The Type ...

Encountered a RunTime Error when attempting to Lazy Load a module

When attempting to lazy-load a component separately, an unexpected run-time error is occurring. This issue is specifically related to writing loadChildren within the routing module of another component in Angular 6. Any assistance with resolving this error ...

When processing a response from the backend (using express js), cookies are not being received in the browser while on localhost

I'm currently facing some difficulties with implementing authorization cookies within my application. Whenever I attempt to send a GET request to my API (which is hosted on port 8080) from my React frontend (running on port 3000), the cookies that I ...

Make sure to incorporate certain node_modules folders within Babel 7

My issue involves a dependency located in the node_modules directory that requires compilation through Babel. Despite upgrading my stack, I am unable to get Babel to compile the dependency. Current versions: @babel/core 7.5.4 webpack 2.7.0 Here is my w ...

Creating a dynamic progress bar that scrolls for multiple elements

I am currently working on implementing a scrolling progress bar to show users how much of an article within a div they have read. For reference, something similar can be seen on this site. I have created my custom progress bar and coded it on fiddle, whe ...

Newbie's guide to setting up babel for material-ui in Next.js!

Helpful Resources: Click here "For better bundle size optimization, create a .babelrc.js file in your project's root directory: const plugins = [ [ 'babel-plugin-transform-imports', { '@material-ui/core': { ...

Failure to override prototype method

Why isn't the code `foo` displayed in the console? I expected the `foo` method in the child class to override the parent class. Why did that not happen? function parent(){ } parent.prototype.foo = function(){ console.log('foobar'); }; ...

Triggering server-side code (node.js) by clicking a button in an HTML page created with Jade

I am currently working on developing a web application and have encountered an issue where I need to execute some server-side code when a button is clicked (using the onClick event handler rather than the Submit button). My tech stack includes Node.js, Exp ...

What is the best way to dynamically insert columns into HTML code?

This is an example of my HTML code: <div class="row text-center"> <div class="col h4">We Collaborate With:</div> <div class="col">company1</div> <div class="col">company2</div> ...

Tips for declaring a non-reactive instance property in Vue.js with TypeScript

I am currently in the process of transitioning my Vue.js components to TypeScript. In accordance with the recommendations provided in the documentation, I attempted to utilize Vue.extend() for my component implementation. The code snippet for my component ...

How can I show the most recent x floating point values on a chart using ChartJS?

I'm currently working on a Vertical Bar Chart using react-chartjs-2. I have an array of numerous float numbers saved. My attempt to utilize the chartjs callback option to only show the last value on the graph failed. The problem lies in the fact th ...

I'm trying to retrieve information from openweathermap in order to show it on my app, but I keep running into an error that says "Uncaught RangeError: Maximum

I recently created a div with the id 'temporary' in order to display data retrieved from the openweathermap.org API. However, I am encountering an error in the console and I'm not sure why. This is my first time working with APIs and I would ...

Node server quickly sends a response to an asynchronous client request

Apologies for my lack of writing skills when I first wake up, let me make some revisions. I am utilizing expressjs with passportjs (local strategy) to handle my server and connect-busboy for file uploads. I believe passport will not have a role in this pr ...

Adding URIs to a post request using JavaScript

I'm struggling to understand how to include URIs in a POST request, similar to this API request: link to example This is my current request, but it's not functioning properly fetch(endPoint, { method: "POST", headers: { Authorization ...