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.