0

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!

2
  • [ [ { key: value} ], [ { key: value}, { key: value} ], [ { key: value}, { key: value} ] ] Is this your result array? Commented May 10, 2017 at 14:58
  • The array dont seems to be in proper format Commented May 10, 2017 at 14:59

2 Answers 2

4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Most elegant solution ever.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.