Reputation: 1841
I have a project where in one instance I am returning an object that contains three separate arrays of objects.
Like so...
[
Array 1:[
{ key: value}
],
Array 2:[
{ key: value},
{ key: value}
],
Array 2:[
{ key: value},
{ key: value}
]
]
What I'm trying to do is take this multi array of objects and make it a single array containing the objects from all three.
I'm trying to do this using angular.forEach and loop through them and push them into a new array, but it's not working.
var newArray = [];
angular.forEach(result, function(value, key){
newArray.push(value);
});
return newArray;
Could really use some advice on this one!
Thanks!
Upvotes: 0
Views: 51
Reputation: 48407
You can use reduce
method, which accepts a callback
provided function.
var arr = [[{ key: 'value'}],[{ key: 'value'},{ key: 'value'}],[{ key: 'value'},{ key: 'value'}]]
var array = arr.reduce(function(obj,item){
obj.push(...item);
return obj;
},[]);
console.log(array)
Upvotes: 0
Reputation: 122077
You can use concat()
and spread syntax.
var arr = [[{ key: 'value'}],[{ key: 'value'},{ key: 'value'}],[{ key: 'value'},{ key: 'value'}]]
var result = [].concat(...arr);
console.log(result)
Upvotes: 4