Combining Various Items Retrieved from Fetch Request

I am attempting to merge multiple objects retrieved from an API by grouping them based on their id and values, ensuring that any modifications are only applied to individual objects rather than affecting all of them.

Here is my latest approach:

const carIds = [7, 78, 34, 59];

let url = "";
carIds.map(id => {
  url = `https://example.com/api/reports?carId=${id}`;

  fetch(url)
    .then(response => response.json())
    .then(data => processCarData(data))
    .catch(error => console.error(error));
});

const processCarData = data => {
  const reports = data.cars[0].car.car_makes;

  let result = reports.reduce(function(r, a) {
    r[a.car_make_id] = r[a.car_make_id] || [];
    r[a.car_make_id].push(a.car_model);
    return r;
  }, {});
};

The responses I receive from the API resemble the following format (without commas included in the API response):

{"id":1,"car_make":[{"car_make_id":"7","model_year":2000,"car_model":"Viper"}]}
{"id":2,"car_make":[{"car_make_id":"7","model_year":1997,"car_model":"Elantra"}]}
{"id":3,"car_make":[{"car_make_id":"7","model_year":2011,"car_model":"Yukon"}]}
{"id":4,"car_make":[{"car_make_id":"7","model_year":1996,"car_model":"Suburban 2500"}]}
{"id":5,"car_make":[{"car_make_id":"7","model_year":1995,"car_model":"G-Series G10"}]}

In these responses, the car_make_ids match but the car_models vary.

The expected output should be:

{
  car_make_id: 7,
  values: ['Viper', 'Elantra', 'Yukon', etc...]
}

However, the current output appears as follows:

{
  7: ['Viper']
}
{
  7: ['Elantra']
}
{
  7: ['Yukon']
}
{
  7: ['Suburban 2500']
}

Would appreciate any suggestions on how to achieve the desired outcome. Thank you in advance.

Answer №1

Here's a possible solution:

const finalResult = reports.reduce((accumulator, currentValue) => {
    if (accumulator["car_make_id"] !== currentValue.car_make_id){
      accumulator["car_make_id"] = currentValue.car_make_id;
      accumulator["values"] = [];
    }
    accumulator["values"].push(currentValue.car_model);
    return accumulator;
  }, {});

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

Unable to generate StumbleUpon traffic for a URL through AJAX due to the API returning text/plain

I'm attempting to acquire StumbleUpon views for a specific URL using $.ajax. This is the API I am utilizing: http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http://example.com/ Here is the complete code snippet: $.ajax({ type: "GET ...

Ways to bypass mongoose schema validation while making an update request in the API

In my model, one of the fields is specified as providerID: { type: Number, required: true, unique: true }. The providerID is a unique number that is assigned when inserting provider details for the first time. There are situations where I need to update ...

Problem with routing: Request parameters not being collected

I am currently working on a project to create a wikipedia clone. Initially, I set up an edit route that looks like this: router.get('/edit/:id', function(req, res){ var id = req.params.id; console.log(id); models.Page.findById(id, ...

Adjustable Scroll Bar

Could anyone help me find a component similar to the resizable scrollbar on Google Finance? Check out this link: http://www.google.com/finance?q=EURUSD&ei=bhM_UKDXF-aIWqAPVNQ You can see it below the chart. If you know where I can find something like ...

Exporting JSON data to CSV or XLS does not result in a saved file when using Internet Explorer

Presented below is the service I offer: angular.module('LBTable').service('exportTable', function () { function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel, fileName) { //If JSONData isn't an object, parse the ...

Is there an issue with loading CSS and JavaScript in mobile view on a website built with CodeIgniter?

My experience with codeigniter has been great so far, but I encountered an issue when trying to view my work on different devices. Here is the problem: Web: Broswer View | Browser (Responsive Design View) Mobile: Screenshot 1 | Screenshot 2 _htaccess: ...

What could be the reason behind receiving a TypeError upon refreshing the page, where it claims that a state is not found even though that may not be the actual situation?

Within my application, I have a component called Wall. Users are redirected to the Wall component after successfully logging in from the Login component. In the Wall component, I am retrieving and displaying the user's name that they used during regis ...

Creating dynamic controls in edit template of KendoUI ListView at runtime

Linked to this inquiry, I am interested in replicating the same functionality within a ListView rather than a kendo Grid. My attempt can be viewed here. The editing template switches between different controls based on the initial model value during edit m ...

Encountering an unexpected end of input error while making an API call using the fetch()

I'm looking to transition an API call from PHP to Javascript for learning purposes. Unfortunately, I can't make any changes on the API side as it's an external source. When attempting to use fetch() due to cross-origin restrictions, my scrip ...

I am looking to implement a dropdown menu that appears after clicking on an image. Any suggestions on how to achieve this using

I've been experimenting with adding a dropdown class, but I'm feeling a bit lost on where to start. Here's a snippet of code that shows what I'd like to do to add a dropdown menu: <span id="dropdown-info" ng-init= "myVar='i ...

Retrieving Array keys from PHP using jQuery

As a beginner in jQuery, I am eager to learn how to retrieve Array keys from a php file using jQuery. Currently, I have jQuery code set up to send input to file.php and execute a query on every keyup event. When file.php echoes the result, it looks somet ...

Looking to retrieve the full browser URL in Next.js using getServerSideProps? Here's how to do

In my current environment, I am at http://localhost:3000/, but once in production, I will be at a different URL like http://example.com/. How can I retrieve the full browser URL within getServerSideProps? I need to fetch either http://localhost:3000/ or ...

When a user clicks on an anchor tag in a React component, the input element will automatically receive

I am currently working with two components: Within my parent component, I have the following set up: // Initialize focus object as false // Import Child Component and React libraries const parent = React.createClass({ getInitialState: function() { ...

Switch out the name of multiple elements with mootools

Is there a Moo tool that can replace multiple element IDs? I currently have the following code: $$('myelement').each(function(el){ var get_all_labels = el.getElements('label'); var get_label_id = get_all_l ...

Extracting Query Parameters from a Successful Ajax Call in Javascript

How can I extract data from the success response? Take a look at my code snippet: $.ajax({ async: 'true', url: 'https://exampleapi.com/product', type: 'GET', data: {page: idQuery}, success:(response => { v ...

Is it possible for third party packages to function properly without the node_modules directory?

Whenever we push our code to GitHub or any other remote repository service, we make sure to exclude the node_modules folder. This begs the question: how are all the third-party libraries functioning on the hosted website if the node_modules folder is not ...

inject a $scope object into a view when a button is clicked

Right now, I am using an array as a $scope object $scope.data { item1: "Value", item2: "Value Alt" } Every item corresponds to a form input with a default value. My goal is to create a new form from the same data set upon an ng-click event while main ...

Backend data displayed on carousel presents either all images or none at all

I am currently working on a Django project that involves displaying a list of images in a Carousel format within my template. I have encountered an issue with setting the active class for the Carousel items. When I include the "carousel-inner active" clas ...

Adding Bootstrap modal content to a webpage before it renders is a simple process that involves preloading the

When using Bootstrap modal, is it possible to load a remote URL along with the parent page without needing to click on a button? ...

Prevent sticky div from overlapping with footer

I currently have a social link menu that is fixed to the left side of my page, structured like this: <footer id="colophon"></footer> <div> <nav> <ul id="social"> <li>Link1</li> ...