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}]]
A recursive solution for deep (nested) flattening:
A bit more compactly with ES6:
For fun, using a generator named
F
for "flatten", to lazily generate flattened values:For those not familiar with generators the
yield *
syntax yields values from another generator.Array.from
takes an iterator (such as results from invoking the generator function) and turns it into an array.If you only need simple flatten, this may works:
For more complex flattening, Lodash has the flatten function, which maybe what you need: https://lodash.com/docs#flatten
Array.prototype.concat(...searchData)
OR
[].concat(...searchData)
Calling function
Result