JavaScript 展平对象数组的数组 [英] 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 注销了上面的截图,但是 m 注销了 [ ]
searchData logs out the screenshot above, but m logs out [ ]
这里是searchData的实际内容:
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}]]
推荐答案
您可以使用 Array.concat 如下所示:-
You can use Array.concat like bellow:-
var arr = [['object1', 'object2'],['object1'],['object1','object2','object3']];
var flattened = [].concat.apply([],arr);
flattened
将是您预期的数组.
ES 2020 提供了 flat,也flatMap 如果你想迭代,到平面列表列表:
ES 2020 gives the flat, also flatMap if you want to iterate over, to flat lists of lists:
[['object1'], ['object2']].flat() // ['object1', 'object2']
这篇关于JavaScript 展平对象数组的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!