在Javascript / NodeJS中连接未知数量的数组
我有一个我的控制器中的一个函数,我填充一个文档的引用数组,当填充时,它们自己embedded数组。
这是一个例子:
mongoose填充函数给了我一个对象数组。 在每个对象中是一个数组:
[name:Test,array:[1,2,3,4,5]},{name:TestAgain,array:[1,2,3,4,5]},{name:Test ^ 3,array: [1,2,3,4,5]},{…
期望的输出将是:
[1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,…]
我需要连接所有的“数组”在填充引用。 我怎么能不知道有多less个数组呢?
作为参考,这里(一般)是什么我的function看起来像:
exports.myFunctionName = function ( req, res, next ) Document.findOne({ 'document_id' : decodeURIComponent( document_id )}).populate('array_containing_references').exec(function( err, document) { //Here I need to concatenate all of the embedded arrays, then sort and return the result as JSON (not worried about the sorting). });
假设你的input是在document
variables中,试试这个:
var output = document.reduce(function (res, cur) { Array.prototype.push.apply(res, cur.array); return res; }, []);
或这个:
var output = []; document.forEach(function(cur) { Array.prototype.push.apply(output, cur.array); });
你想采取每个文件,并从它做一个属性。 听起来像Array.prototype.map的一个很好的用例!
map
将获得每个文档的array
值,并返回这些值的数组。 但是,你不需要一个嵌套的数组,所以我们只需使用Array.prototype.concat
来平滑它。 你也可以使用lodash / underscore.js flatten
方法。
var a = [ { name: 'test1', array: [1, 2, 3, 4, 5]}, { name: 'test2', array: [1, 2, 3, 4, 5]}, { name: 'test3', array: [1, 2, 3, 4, 5]} ]; var results = Array.prototype.concat.apply([], a.map(function(doc) { return doc.array; })); document.body.innerHTML = results;