Reputation: 13
I am doing an http call to get data from a database. There are 6 types that have to be called individually.
$scope.getAll = function() {
var url = 'http://someurl/';
varl allObjects = [];
$scope.types.forEach(element => {
http({
method: 'GET',
url: url + element.name
}).then(function successCallback(response) {
allObjects.push(response.data);
}, function errorCallback(response) {
// this doesn't apply to my issue
});
$scope.allObjects = allObjects;
}
That return like the following JSON object:
[{},
[{ "label":"myLabel",
"types": {
"source":{"url":"some url, "storage":"some storage"}}},
{ "label":"myLabel",
"types": {
"source":{"url":"some url, "storage":"some storage"}}}],[{ more objects}],[{ more objects}],],
All objects return the same structure with nested arrays. The issue I need help solving is every time it goes through an iteration of the type, it adds it as an array of objects. I need it to be added just as a new object, not an array of objects. ie:
What I am getting:
[{}, [{first iteration}], [{second iteration}], [{etc}]]
What I need:
[{first iteration}, {second iteration}, {etc}]
Upvotes: 1
Views: 58
Reputation: 827
You can achieve this using the Array.prototype.flat()
function which compresses an array of arrays to a certain depth level. The depth for your situation would be 1
which is already set as default
var arr = [
{},
[
{
test: 1
}
],
[
{
second: 2
}
],
[
{
etc: 3
}
]
];
console.log(arr.flat());
The function essentially flattens the arrays in the array, only going in depth of 1, if you had arrays in the arrays you wanted to flatten you'd change the depth to 2
.
The empty object will still be there however. You can make a check to get rid of those after flattening.
Upvotes: 1