Merging the outcomes of a JSON call

Presently, I have an async function that returns a JSON response in the form of an array containing two objects. Please refer to the screenshot.

https://i.sstatic.net/gCP8p.png How can I merge these objects to obtain:

[{resultCount: 100, results: Array(100)}]

I attempted the following code snippet:

   var combinedResults = jsonResponses.map((acc, item) => {
       acc.resultCount += item.resultCount;
       acc.results += item.results;
       return acc;
   });

However, the outcome looked like this:

https://i.sstatic.net/BEEPy.png

Oh no!

If you could provide any assistance, it would be greatly appreciated!

    export function getDoorstepsSongs () {
      return async dispatch => {
        const page1 = 'https://itunes.apple.com/search?country=us&media=music&limit=50&attribute=songTerm&term=door&sort=ratingIndex'
        const page2 = 'https://itunes.apple.com/search?country=us&media=music&limit=50&offset=50&attribute=songTerm&term=door&sort=ratingIndex'
    
        const jsonResponses = await Promise.all([
          fetchJsonP(page1),
          fetchJsonP(page2),
        ]).then(responses => {
          return Promise.all(responses.map(res => res.json()))
        }).catch(console.error)
    
        console.time('processing songs')
    
        //
        // jsonResponses contains the results of two API requests
        //
        // 1. combine the results of these requests
        // 2. sort the results with lib/sortSongs.js
        //
    
        const sortedSongs = sortSongs(combinedResults)
    
        console.timeEnd('processing songs')
    
        return dispatch({
          type: 'GET_DOORSTEPS_SONGS_SUCCESS',
          songs: sortedSongs,
        })
      }
    }

Answer №1

Try implementing Array.reduce

let data = [{numOfItems: 3, items: [5,6]}, {numOfItems: 4, items: [7,8]}];

let output = [data.reduce((prev, current) => ({numOfItems: prev.numOfItems + current.numOfItems, items: [...prev.items, ...current.items] }))];

console.log(output);

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

Strange glitches and slow loading problems plaguing website. (GoDaddy)

TackEmporium.com Lately, I have been revamping my website, which was originally given to me by a friend. I have been making slight adjustments to update its appearance while keeping its classic look with enhanced resolution and cleaned-up HTML5 code. Rec ...

displaying data from multiple sources using JSON in amcharts

I am trying to implement AmChart and retrieve data for my charts from MySQL using JSON. Here is the JavaScript source code I am using: AmCharts.ready(function () { //generateChartData(); createStockChart(); }); function createStockChart() { ...

In Java, what is the process of converting a string in the format {a=2 ,b=5} to a JSON object in the format {"a":2 , "b":5}?

I have received the outcome as {a=2 ,b=5} following the evaluation of a SpEL expression. I would like to convert it into json format. Can anyone provide guidance on how to achieve this? Your assistance is greatly appreciated! ...

Include an additional tag solely by using a specific set of keys predetermined in advance

After getting inspiration from Stackoverflow, I decided to enhance my text-box with a tagging feature. The first step was downloading and adding the http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js file to my ASP.NET web folder, allowing me to u ...

The countdown feature is failing to update despite using the SetInterval function

My goal is to develop a countdown application using Atlassian Forge that takes a date input and initiates the countdown based on the current date. For instance, if I input "After 3 days from now," I am expecting the result to continuously update every seco ...

Implement a jQuery slideshow with a full background image, aiming to set up a clickable link on the final image of the

Could someone please help me with a query I have regarding a background image slide show using jQuery code? I have set up a slide show with multiple images and would like to make the last image clickable. Is it possible to achieve this specific functionali ...

Discover the versions of key libraries/modules within the webpack bundle

Is it possible to identify all the libraries, scripts, or modules included in a webpack bundle through the developer's console of a website that is already running, without access to its codebase? Additionally, is there a way to determine the version ...

The process of returning parameters from a modal view in Ionic

I am currently facing an issue with my modal view that is used for user login. I need to retrieve the user id from the modal and pass it back to the view behind. I attempted using $state.go but it was unsuccessful. Additionally, using ng-href would not wor ...

Managing dynamic input texts in React JS without using name properties with a single onChange function

Dealing with multiple onChange events without a predefined name property has been challenging. Currently, one text input controls all inputs. I have come across examples with static inputs or single input functionality, but nothing specifically addressin ...

Guide on incorporating custom items alongside default items in the Context Menu of Handsontable

I attempted to utilize handsontable and am interested in incorporating custom additions to the context menu. While there are numerous tutorials on how to implement custom menus, they often overlook the default items. In an effort to address this issue, I ...

How are "new" and "prototype.constructor" related in the realm of Javascript?

Many people have discussed this issue, but unfortunately, I haven't been able to find a solution yet. Here is a snippet of Javascript code regarding inheritance from a book: function Car() { var self = this; self.type = "Car" self.go = funct ...

Remove user from firebase with Admin SDK

I need help understanding how to remove a user from my admin panel using the Firebase Admin SDK. When attempting to delete a user, I encountered this error: Uncaught (in promise) ReferenceError: uid is not defined at eval (ManageCustomer. ...

Retrieving URL Parameters in Meteor-React's createContainer

In my React/Meteor application that utilizes react-router, I am attempting to pass the URL parameters (for example, /user/P8HDQMAuapRESoWo6) into createContainer. This function fetches the result of the initial MongoDB query: let user = Meteor.users.findO ...

Managing field placement as the table height grows: tips and tricks

I am encountering an issue with my dynamic form. When I click on the add button, a new row is added to the table. However, once there are more than 6 rows added, the table height starts covering the fields. How can I go about setting this so that the field ...

Display an image in an Angular application using a secure URL

I am trying to return an image using a blob request in Angular and display it in the HTML. I have implemented the following code: <img [src]="ImageUrl"/> This is the TypeScript code I am using: private src$ = new BehaviorSubject(this.Url); data ...

Pass the ID of the <a> element from one function to another

I am a beginner in javascript/jQuery, so please be patient with me if my question seems too simple for you and too challenging for me. I have a function that I won't post the entire code for because it would make this too lengthy. Another function ...

Navigating through nested data structures: accessing a dictionary within a list within another list

Currently, I am working with JSON data and attempting to parse it using Python. Within my code, there is one particular section where I am struggling with the syntax. Here is a snippet of the JSON data: u'line_items':[ { u' ...

Experiencing difficulties with a cross-domain jQuery/AJAX service request

After extensively researching various threads both on this platform and elsewhere, I have been trying to successfully execute a cross-domain AJAX call. The scenario involves a Restful WCF service that simply returns a boolean value. The service is configur ...

Apply bold formatting to the HTML text only, leaving the EJS variable untouched beside it

https://i.sstatic.net/X36eG.png Is there a way to format the text for "Guest signed up" and "Guests attended" in bold while keeping the values normal? Here is my current code: <li class="list-group-item">Guests signed up: <%= guestSignu ...

Issue with Angular Factory not being invoked

I am currently using a tutorial to create a MEAN app with Google Maps. However, I have encountered an issue where the map is not appearing on the page. Surprisingly, there are no errors in the browser console and even when debugging with node-inspector, I ...