Merge JSON objects sequentially within a loop without using JQuery

Update: I have corrected the errors in the sample code provided. It turns out that the issue was caused by an extra 'records' in

var jsonVar = jsonVar.concat(results.records);

Is there a way to concatenate multiple JSON objects within a loop? Concatenating two JSON objects can be done like this:

var json1 = {
 "records": [{
 "id": 28100988,
 "work_text_reviews_count": 13,
 "average_rating": "3.10"
 }, {
 "id": 10280687,
 "work_text_reviews_count": 80,
 "average_rating": "3.87"
 }]
}

var json2 = {
 "records": [{
 "id": 16135639,
 "work_text_reviews_count": 0,
 "average_rating": "0.00"
 }, {
 "id": 17978337,
 "work_text_reviews_count": 2414,
 "average_rating": "3.76"
 }, {
 "id": 360721218,
 "work_text_reviews_count": 4924,
 "average_rating": "3.98"
 }]
}


var json3 = json1.records.concat(json2.records);

If I wanted to add a third JSON object, I could simply include .concat(json3.records) but how do I go about concatenating JSON objects dynamically in a loop?

For example: Assume values.length = 5, it means that 5 JSON objects need to be concatenated.

for (var i=0; i<values.length ; i++) {

response= UrlFetchApp.fetch(url);
Utilities.sleep(1000);
var results = JSON.parse(response);

// This is now functioning correctly (I had made a mistake here)
var jsonVar = jsonVar.concat(results.records); 

}

Answer №1

One possible solution could be the following code snippet:

let jsonData = [];
for (let index=0; index<values.length ; index++) {

  const resultData = UrlFetchApp.fetch(url);
  Utilities.sleep(1000);
  let results = JSON.parse(resultData);

  jsonData = jsonData.concat(results.records); 

}

However, caution should be taken as UrlFetchApp.fetch() operates asynchronously. This implies that the resultData may not always be initialized correctly if the process takes longer than 1000ms.

Answer №2

In the world of programming, a JSON object essentially translates to a JavaScript object that offers the flexibility of dynamically assigning names to objects.

  for (var index=0; index < values.length ; index++) {
  json[index].entries.concat(json[index + 1].entries)
  }

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

Mongoose reminds us that static is not a method

I encountered an error message stating that "product.try() is not a function." Interestingly, when I immediately invoke the try() function, it works fine and node recognizes the model "product." I'm starting to wonder if there's something funda ...

Start the CSS3 animation in reverse right away

I am trying to achieve a "flashing" effect by adding the .shown class to my #overlay, causing the opacity to fade in for 2 seconds and then immediately reverse, fading out for another 2 seconds. After experimenting with removing the class, I found that it ...

The extent of a nameless function when used as a parameter

I am currently developing a straightforward application. Whenever a user hovers over an item in the list (li), the text color changes to green, and reverts back to black when the mouse moves away. Is it possible to replace lis[i] with this keyword in the ...

Changing AngularJS API requests from PHP to JSON format

Hey there, I have an app that is capable of connecting to an API. However, it currently can only get API requests from a PHP file. I am looking to modify the code so that it can accept .json API files instead. Factory factory.readProducts = function(){ ...

What is the best way to transfer a variable from a template to views.py?

Is there a way for me to pass the oobcode value to the postresetusername function in views.py? reset_username.html <script type="text/javascript"> var oobcode; function func(){ oobcode = localStorage.getItem("storageName"); ...

Making an Ajax request that returns JSON data, which then needs to be appended into a select box

Struggling with including Json data in a select box has been an issue for me. Despite successfully retrieving the json data within my Ajax call, the problem persists. The ID appears in the select box as an option along with the name, which is not what I de ...

Loading data with React Router every time

I'm still getting the hang of React and React Router. On the home page (home component), data is loaded from the server via an AJAX request to display the information. However, when users navigate within the app using React Router and return to the ...

Issue with Material-UI tab when using a datatable within it's content

I implemented the Simple Tabs feature from Material-UI with a Tab containing a Datatable using React-Data_Table. However, I noticed that this particular tab is not responsive like the others when the table is full. Empty Full Here's a snippet of th ...

You are limited to storing only up to 2 items in the localStorage

My goal is to save items in local storage as an array of objects. Initially, it works perfectly and stores the first element in local storage as needed. However, I am facing an issue where I cannot store more than one element. Below is the code block that ...

Tips for keeping the options menu visible even when the video is paused

As I was creating my own customized Video player, I encountered an issue where I wanted the options bar/menu to disappear when the user became inactive. While I have managed to achieve this functionality, I still require the option bar to remain visible ...

tutorial on updating database status with ajax in Laravel

Currently, I am using Laravel in my project and I need to modify the patient's status when they schedule an appointment with a doctor. The patient can have one of three statuses: Accept, Waiting (automatically assigned when the patient selects a date ...

The cascade option in TypeORM entities

In my project, I am working with two entities named Order and Address, which are connected through a @ManyToMany relationship. For the Address entity: @ManyToMany(() => Order, (order) => order.address, { cascade: true }) @JoinTable() order: Order; ...

How can Tweepy be utilized to extract the integer count and incorporate it?

Hope all is well with everyone here. My apologies if this question has been addressed previously, but I am currently working on the following task. cursor = tweepy.Cursor( api.search_tweets, q = '"Hello"', lang = 'en&ap ...

Error encountered in AngularJS when utilizing the Flickr API with the parameter "nojsoncallback=1": Unexpected token Syntax

My AngularJS application is trying to access the Flickr API. I need the data in RAW JSON format without any function wrapper, following the guidelines provided in the documentation by using &nojsoncallback=1. However, I keep encountering a console er ...

Is there a way to access Instagram using Javascript for login?

Goal I am determined to automate the Instagram login process using Javascript by filling in the username and password fields, then clicking the log in button. My Attempts (with correct credentials): Access Instagram Login Page document.querySelector(&a ...

Setting up Firebase in Node.js with Express.js is a key step in developing

Setting up a Firebase instance (not firebase-admin) in Node.js. import { initializeApp } from 'firebase/app'; const firebaseConfig = { //... }; const app = initializeApp(firebaseConfig); This method may not be effective as Node.js uses Commo ...

Extract particular elements from an array and transform them into a new array

Presented below is an array: [{ "title": "Apple iPhone 7 Plus 32 GB", "category": "phone", "brand": "apple", "condition": "Used", "price": 800, "id": 0, "description": "Apple" }, { "title": "Apple Ipad Air 32 GB", "category": "tablet", "brand ...

Modifying deeply nested properties in Vue.js

Within my Vue.js application, I've created a method to update the src attribute of images whenever a file is chosen from a file input field. This method is triggered like so: <input type="file" accept=".jpg,.png" @change="updateSrc($event, 'p ...

Merging two distinct arrays of objects in JavaScript can be achieved by utilizing various methods and

I have a challenge where I need to merge two arrays of objects in a nested way. var array1=[{ PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2& ...

Retrieve a user entry from MongoDB based on the provided email address

Issue with User.findOne Function I am facing an issue where despite having the data "user([email protected])" in the database, the User.findOne function always returns null. I have a node server running in the background and although req.body correct ...