What is the best way to append multiple JSON objects to a single array within a loop?

My current task involves making external API calls that return JSON objects. Once all the calls are completed, I intend to write the collection of JSON objects to a file. However, I'm encountering an issue where the data is being written to the file in the incorrect format.

UPDATE: The findPrices() function is invoked within a loop.

priceSearch1Array = [];

function findPrices(res) {

  (api.get({
    origin: A,
    destination: B,
  }).then(function(response) {

    priceSearchVar = JSON.stringify(response.result.data);
    priceSearch1Array.push(priceSearchVar);

  }).catch(function(error) {
    console.log('error and continue' + error);
  }))

}

Once all API calls are made, the array containing the data is saved to a file.

fs.writeFileSync('api/data/destinations3.json', priceSearch1Array);

The current output looks like this:

[{flight:"data", segments: { price:"23.22"}}],
[{flight:"data", segments: { price:"78.45"}}],
[{flight:"data", segments: { price:"48.45"}}]

However, I require the data to be written in the following format:

[ 
  {flight:"data", segments: { price:"23.22"}},
  {flight:"data", segments: { price:"78.45"}},
  {flight:"data", segments: { price:"48.45"}} 
]

I need the JSON objects to be presented as a list and then added to the file rather than having each object stored as an individual array. Is there a way to achieve this?

Answer №1

    function fetchAndStorePrices(result) {

      (api.get({
        origin: startingPoint,
        destination: finalDestination,
      }).then(function(response) {
        let prices = []

        try {
          // retrieve and convert the data into JSON format
          prices = fs.readFileSync('api/data/destinations3.json', 'utf8')
          prices = JSON.parse(prices)
          prices = Array.isArray(prices) ? prices : [prices]
        } catch(err) {}

        const responseData = response.result.data
        const combinedPricesArray = JSON.stringify([ ...prices, responseData ])

        fs.writeFileSync('api/data/destinations3.json', combinedPricesArray);

      }).catch(function(error) {
        console.log('encountered error but continuing...' + error);
      }))

    }

Answer №2

It seems that the complexity of the code structure might be causing some confusion when trying to troubleshoot the issue. I have reorganized the code for this example, although it may not be necessary to resolve the problem you are facing

There are a couple of issues that could be contributing to the problem:

Firstly, we are dealing with an array of arrays of objects instead of just an array of objects. This can be easily rectified by flattening the array as demonstrated in the function below.

Secondly, writing the raw object to a file can cause problems. Based on my understanding and some testing, fs will write the data as a string, resulting in simplistic conversion where the objects appear as [Object object]. To avoid this, we can use JSON.stringify to get a more appropriate conversion. The example provided simulates the fs and api calls, offering a basic idea.

I have also modified the code to utilize map and Promise.all instead of array push from a loop. This approach may be easier to comprehend; if it is unclear, please leave a comment and I will elaborate further.

const api = {
  get: data => new Promise(res => {
    setTimeout(() => res([data]), 1000)
  })
}

const fs = {
  writeFileSync: (location, data) => {
    console.log(
      `writing data ${data} to ${location}`
    );
    console.log('=====================');
  }
}

const data = [
  {A: 'test', B: 'another test'},
  {A: 'test2', B: 'another test2'},
];

const makeApiCallFromDataItem = dataItem => api.get({
  origin: dataItem.A,
  destination: dataItem.B,
});

const callApiForAllDataItems = data => Promise
  .all(data.map(makeApiCallFromDataItem))

const flatten = dataIn => dataIn.reduce((prev, curr) => [
  ...prev,
  ...curr
])

callApiForAllDataItems(data)
  .then(data => {
    fs.writeFileSync('api/data/destinations3.json', data)
  })
  
callApiForAllDataItems(data)
  .then(data => {
    fs.writeFileSync('api/data/destinations3.json', JSON.stringify(data))
  })
  
callApiForAllDataItems(data)
  .then(data => {
    const flatData = flatten(data);
    fs.writeFileSync('api/data/destinations3.json', JSON.stringify(flatData))
  })

Answer №3

Consider replacing the line

priceSearchVar = JSON.stringify(response.result.data);
with simply
priceSearchVar =response.result.data
and switch
priceSearch1Array.push(priceSearchVar)
to
priceSearch1Array.push(JSON.stringify(...priceSearchVar))

Alternatively, you could condense it into a single line like this:

priceSearch1Array.push(JSON.stringify(...response.result.data))

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

Navigating Links with Python Selenium Loop

Just starting out with Python and coding in general... This section of code enables me to locate all the elements I want to click on (clicking a link opens a new tab) from selenium import webdriver import time driver = webdriver.Chrome() driver.get("htt ...

Ways to implement debounce in handling onChange events for input fields in React

I've been attempting to implement debounce functionality in my React app without relying on external libraries like lodash or third-party node modules. I've tried various solutions found online, but none have worked for me. Essentially, in the h ...

Designing a split navigation bar in Django using unique styling for each section (HTML, CSS, and Javascript)

In my endeavor to design a search button within a responsive navigation bar, I encountered an issue. The navigation bar contains a media query in the CSS file that adjusts it to a dropdown list based on the reader's screen dimensions. Here is the HTM ...

Is designing custom HTML for currency better done through a filter or directive?

After receiving a UX design that specifies the currency symbol should be displayed in gray and the decimal value in black, I took to Google to figure out how to implement it. My solution was creating a straightforward filter: .filter('tnCurrency&apos ...

Encountering an Error while Setting Up NextJS on Vercel

Hello, I'm a newcomer to the world of web development. My current goal is to deploy my first NextJS app on Vercel, but I keep encountering an error. Error: SyntaxError: Unexpected token T in JSON at position 0 at JSON.parse (<anonymous>) ...

I am unable to retrieve dynamic data from the database

Storing data in a MySQL database has been successful for me. I've been utilizing PDO in PHP to fetch the data and then converting it to JavaScript using json_encode. However, I keep encountering the output NaN when implementing a specific scenario. It ...

A step-by-step guide on fetching multiple iframe contents simultaneously with Selenium in Java

Today, I am facing an interesting challenge. I need to extract the page source of a webpage that includes an iframe. Surprisingly, when using the PhantomJSDriver with the code snippet below, I am only able to retrieve either the page content or the iframe ...

Guide for filtering MongoDB results in 15-minute intervals based on timestamp input

I'm faced with a seemingly "simple" issue, but my solution feels unnecessarily complex and I'm struggling to implement it... This is the schema I'm working with: const DensitySchema = mongoose.Schema( { map_id: mongoose.Schema.Types. ...

After npm installation and running the dev command, an error is displayed in the console, despite the project functioning properly on a different

After successfully installing a reliable project on my personal computer and compiling it without any issues, I encountered an error message in the console. Uncaught ReferenceError: regeneratorRuntime is not defined at eval (index.umd.js?e3f3:5) at eval ( ...

Node.js accepts JSON data sent via XMLHttpRequest

I have successfully implemented a post method using xmlhttprequest: var xhttp = new XMLHttpRequest() xhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { console.log('Request finished. Pro ...

display PHP JSON information using jQuery AJAX

I'm completely new to this subject. I have a Json result that looks like the following : { "span": " 1", "numcard": "12", "chan": " Yes", "idle": "Yes", "level": "idle ", "call": "No ", "name": "" } My goal is to ...

How to create a popover in Rails 4 using Coffeescript and Bootstrap?

I need help adding an onclick event to a specific apple element in my Rails application. The code I have is written in CoffeeScript. apple.on 'click', () -> $(this).popover('[data-content="This is the body of Popover"]'); Can som ...

Verify if the data in the Express request is an array

Recently, I've been working on an Express 3.x API server and facing the challenge of implementing support for batch requests at a specific endpoint. Despite not having the control to upgrade to 4.x, I am determined to find a solution. Currently, the e ...

Finding an element with Protractor by executing JS script

My objective is to retrieve a drop-down list of elements. Despite trying Protractor's methods, I struggled to easily locate isolate-span elements. Due to this, I am now turning to JavaScript code: var my_js_element = browser.executeScript(jQuery("td. ...

Restore radio input functionality with a transparent method

I've experimented with various methods, including traditional form reset techniques and jQuery solutions from different sources on the internet without success. Snapshot: The Objective: I am working on a sortable list where users are required to ra ...

Enhancing AngularJs Kendo Grid Detail Template: Dynamically updating content based on selected row in the detail template

Experimenting with the KendoUI AngularJS Grid detail template has been quite insightful. I am currently facing an issue where I want to update a panel based on a row selected in the detail template grid. Although I have successfully set up the onChange ev ...

Tips for handling a nested array of elements that have been deserialized from a JSON string

When an MVC Action receives the following JSON string: [{"id":13},{"id":14},{"id":15,"children":[{"id":16},{"id":17},{"id":18}]}] I've been using the DeserializeObject method within the JavaScriptSerializer class to deserialize it. However, I'm ...

Issue with changing the opacity of a Javascript button style is not functioning correctly

The button's opacity used to change gradually in increments of 0.1 every 500 milliseconds, but now it instantly changes to 0.9 without the delay. Issue: Despite being placed within a window load handler and all elements loading properly, the loop is ...

What is the process for generating a matrix with negative index positions?

I'm looking to generate a unique matrix with numpy by doing the following: np.zeros([800, 200]) Is there a way for me to create a matrix that includes negative indices? For example, a 1600x200 matrix with row indices ranging from -800 to 800? ...

"Attempting to access a variable defined in one pipe results in it being undefined in a

Currently, I am utilizing gulp to process pages for a website. Some of these pages are PHP files, however, after going through the template engine, they all end up with a .html file extension. My intention is to add a property to each file indicating if it ...