Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript flattening an array of arrays of objects

I have an array which contains several arrays, each containing several objects, similar to this.

[[object1, object2],[object1],[object1,object2,object3]] 

Here is a screenhot of the object logged to the console.

What would be the best approach to flattening this out so it just an array of objects?

I've tried this with no luck:

console.log(searchData);     var m = [].concat.apply([],searchData);     console.log(m); 

searchData logs out the screenshot above, but m logs out [ ]

Here is the actual contents of searchData:

[[{"_id":"55064111d06b96d974937a6f","title":"Generic Title","shortname":"generic-title","contents":"<p>The Healing Center offers practical, social, and spiritual support to individuals and families. Services include, but are not limited to: food and clothing, job skills training and job search assistance, auto repair (Saturdays only), mentoring, financial counseling, tutoring, prayer, life skills training, and helpful information about local community services.</p><p>Stay in touch with us:</p>","__v":0},{"_id":"5508e1405c621d4aad2d2969","title":"test english","shortname":"test-page","contents":"<h2>English Test</h2>","__v":0}],[{"_id":"550b336f33a326aaee84f883","shortname":"ok-url","title":"now english","contents":"<p>okokko</p>","category":"Transportation","__v":0}]] 
like image 577
byrdr Avatar asked Mar 20 '15 03:03

byrdr


People also ask

How do you flatten a nested array of objects?

flat()” method is embedded in ES6 that enables you to “flatten” a nested JavaScript Array. This method returns a new array in which all of the elements of sub-arrays are concatenated according to the specified depth. Here, the “Array” object will invoke the “flat()” method while passing “depth” as an argument.

How do you flatten an array of arrays in Java?

Create an empty list to collect the flattened elements. With the help of forEach loop, convert each elements of the array into stream and add it to the list. Now convert this list into stream using stream() method. Now flatten the stream by converting it into array using toArray() method.


1 Answers

You can use Array.concat like bellow:-

var arr = [['object1', 'object2'],['object1'],['object1','object2','object3']]; var flattened = [].concat.apply([],arr); 

flattened will be your expected array.

ES 2020 gives the flat, also flatMap if you want to iterate over, to flat lists of lists:

[['object1'], ['object2']].flat() // ['object1', 'object2'] 
like image 78
Mritunjay Avatar answered Sep 17 '22 03:09

Mritunjay