In Google Apps Script, JavaScript is used to identify each character in an array as true by implementing the method ".hasOwnProperty(i)"

Behold the following array:

{"C8_235550":
    {"listing":"aut,C8_235550_220144650654"},
"C8_231252":
    {"listing":"aut,C8_231252_220144650654"}}

This data was retrieved via a GET request from a Firebase database using Google Apps Script.

  var optList = {"method" : "get"};
  var rsltList = UrlFetchApp.fetch("https://dbName.firebaseio.com/KeyName/.json", optList );
  var varUrList = rsltList.getContentText();

Take note of the .getContentText() method.

I am questioning if the array has been converted into just a string of characters. When iterating over the returned data, each character is being added individually, causing the JavaScript code to not identify key/value pairs.

Here is the implementation of the FOR LOOP:

dataObj = The Array Shown At Top of Post;
var val = dataObj;
var out = [];
var someObject = val[0];

for (var i in someObject) {
  if (someObject.hasOwnProperty(i)) {
    out.push(someObject[i]);
  };
 };

The result from the for loop appears like this:

{,",C,8,_,2,3,5,5,5,0,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,5,5,5,0,_,2,2,0,1,4,4,6,5,0,6,5,4,",},,,",C,8,_,2,3,1,2,5,2,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,1,2,5,2,_,2,2,0,1,4,4,6,5,0,6,5,4,",},}

I'm perplexed whether the array has been transformed into a string rather than remaining an array. Should I convert it back to its original form? JSON perhaps? I've experimented with various JavaScript array methods, but none seem to yield the expected results if the data were treated as an array.

Answer №1

Here is a method for extracting the elements from your JSON string.

As mentioned in other responses, you will need to convert it back into an object and then access its keys and values.

function extractElements(){
  var jsonString = '{"C8_235550":{"listing":"aut,C8_235550_220144650654"},"C8_231252":{"listing":"aut,C8_231252_220144650654"}}';
  var obj = JSON.parse(jsonString);
  for(var key in obj) {
     Logger.log('First-level key: '+key);
     Logger.log('First-level values: '+JSON.stringify(obj[key]));
     for(var subKey in obj[key]){
         Logger.log('Second-level value: '+obj[key][subKey]);
     } 
  }
}

Answer №2

Your data is structured as an object, not an array. To access the field names within the object, you can utilize the

Object.keys() 

function to retrieve a list of keys. From there, you can implement a basic for loop to iterate through the keys and perform necessary actions.

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

Troubleshooting the Cross-Site Request Cookie Problem with PayPal API Integration (Python Django and JavaScript)

For my senior project, I am in the process of building a website and have come across some difficulties while establishing a payment gateway. Everything was functioning correctly the other night; however, now the buttons are failing to display, and I am bo ...

How can I prevent getting stuck in a never-ending React re-render cycle?

I always believed that placing any form of setState within a useEffect call would lead to an endless re-render loop since the useEffect gets triggered on every render. Surprisingly, in my Next.js application, everything seems to be functioning well without ...

Bug allows unauthorized access to password in Bootstrap Password Revealer

Whenever I try to reveal a Bootstrap password using the eye button, my PC freezes. Strangely, an input is automatically added even though there are no codes for it. This auto-increasing input causes my browser to hang and eventually crashes my entire PC. C ...

A comprehensive guide on utilizing the loading.tsx file in Next JS

In the OnboardingForm.tsx component, I have a straightforward function to handle form data. async function handleFormData(formData: FormData) { const result = await createUserFromForm( formData, clerkUserId as string, emailAddress a ...

``There seems to be an issue with implementing the SlideDown feature in JavaScript

I am having an issue with a code where the expected behavior is to slide down a div when a person hovers over text, but it's not working. Can someone please review and identify the cause of this problem? <script type="text/javascript" src="/js/jqu ...

Display multiple markers on a Google Map using google-map-react library

I am currently struggling to display markers on my Google Map using the map function. I have tried various approaches but nothing seems to work. Could there be limitations that I'm not aware of, or am I overlooking something critical? I experimented w ...

Opening a modal in Bootstrap 4 selectpicker depending on the chosen value

I am facing an issue with a selectpicker that has live search functionality. I want to trigger a modal to open only when the user clicks on the option that says "Add new contractor." However, this modal is currently opening for all options, even though I o ...

Resolve the issue with automatically generating SCSS type definitions (style.d.ts) for Preact within a TypeScript webpack setup

Utilizing webpack with Preact 10.x (nearly identical to React) and TypeScript in the VSCode environment. Following an update from Node version 12 to version 14, there seems to be a problem where *.scss files no longer automatically generate their correspo ...

Having trouble with Next.js environment variables not being recognized in an axios patch request

Struggling with passing environment variables in Axios patch request const axios = require("axios"); export const handleSubmit = async (formValue, uniquePageName) => { await axios .patch(process.env.INTERNAL_RETAILER_CONFIG_UPDATE, formVal ...

I'm having trouble grasping the concept of serving gzip-compressed JavaScript and CSS files

Why is it important to serve compressed JavaScript and CSS files? I understand that it reduces file size, but does the browser/webserver have to decompress them to read them? It's been mentioned that the webserver handles the compression. Does this me ...

Guide on integrating JSON and Handlebars partials using Gulp for creating HTML pages

Currently, I am in the process of constructing a static site utilizing Handlebars and Gulp. Here is an overview of my directory setup: app/ content/ intro.json header.json faq.json features.json footer.json ...

Achieve the appearance of table-like alignment without the need for traditional tables

Any ideas on how to achieve the following layout: <table border="0"> <tbody> <tr> <td style="margin-right:5px;"> <h2 id="optiona" class="option optiona optiona2">a. aa </h2> </td> ...

Customize the text on an ASP file upload control

I am trying to utilize an <asp:FileUpload> control in order to obtain the inputstream of a picture for conversion into a byte array and storage in a database. When attempting to add the <asp:FileUpload> control, I noticed it comes with a stati ...

Developing a custom map function in TypeScript

When facing an interview question about creating a custom map function, it's common to be asked to implement it and explain how it works internally using a callback. Map Polyfill // @ts-ignore // eslint-disable-next-line no-extend-native Array. ...

Encountering an issue when attempting to establish a connection to Redis using a cache manager within a Nest

Incorporating the NestJS framework into my project and utilizing Cash Manager to connect with Redis cache. Successfully connected with Redis, however encountering an error when attempting to use methods like set/get which shows 'set is not a function& ...

What are the steps to connecting incoming data to an Angular view utilizing a reactive form?

Hello, I am currently fetching data from an API and have successfully displayed the teacher values. However, I am unsure of how to utilize the incoming array values for "COURSES" in my Angular view. This is the response from the REST API: { "courses ...

Incorporating CSS into JavaScript/Ajax functionality

mypage() is a lengthy function that provides information such as page numbers, total number of pages, and the next page in a pagination system. selectPage() is a JavaScript/Ajax script used to send the current page number to the server. While my CSS file ...

Populating SVG element with information extracted from JSON

Hi there! I'm dealing with a JSON file that contains data for 249 countries, each with their respective iso codes. My goal is to declare the iso code as a variable named 'iso' and the number of visitors as a variable named 'visitors&apo ...

The code snippets in the Vue3 documentation are quite peculiar

As I peruse the Vue 3 documentation, I notice a recurring pattern in how example code is presented for components: Vue.createApp({}) However, my experience with Vue 3 has been different. Instead of the above syntax, I simply use: <script> export d ...

What is the reason behind Java's necessity for an explicit cast on a final variable that was derived from an array?

Commencing with the code provided below... byte number = 1; byte newNumber = number + number; Upon compiling this code, an error will be encountered... Error:(5, 27) java: incompatible types: possible lossy conversion from int to byte ...however, if ...