After spending a considerable amount of time trying various solutions, I am still unable to achieve the desired result. The issue lies in getting an array of objects from service calls and organizing them into a single array for data loading purposes.
The current approach involves fetching data from different services and pushing the results into separate arrays that need to be merged into one. Here is an example:
StatesService.getAreaCities().then(function(response) {
controller.cities = response.data.rows;
controller.areaOptions.push(controller.cities);
});
StatesService.getAreaStates().then(function(response) {
controller.states = response.data.rows;
controller.areaOptions.push(controller.states);
});
controller.areaOptions = [];
My goal is to have the array object structured as shown in this example image. However, currently, the resulting structure does not meet my requirements, as depicted in this illustration.
I attempted to use the reduce()
method with the following code snippet:
var newCities = controller.cities.reduce(function(city){
return controller.city;
}, {});
controller.areaOptions.push(newCities);
Unfortunately, this approach did not yield the expected outcome, as it returned a single object instead of multiple objects containing city properties and values.
EDIT
Fortunately, I was able to find the solution with the help of Lex. By iterating over each object within the array and pushing the property individually, I managed to resolve the issue.
StatesService.getAreaCities().then(function(response) {
controller.cities = response.data.rows;
controller.cities.forEach(function(city){
controller.areaOptions.push(city);
});
});