在Javascript / NodeJS中连接未知数量的数组

时间:2015-07-15 22:07:34

标签: javascript arrays node.js

我在我的一个控制器中有一个函数,我在其中填充了一个文档引用数组,当填充时,它本身就有嵌入数组。

以下是一个例子:

mongoose populate函数为我提供了一系列对象。每个对象中都有一个数组:

[{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 ......]

我需要连接填充引用中的所有“数组”。如何在不知道有多少阵列的情况下才能做到这一点?

作为参考,这里(通常)我的函数是什么样的:

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).
});

2 个答案:

答案 0 :(得分:1)

假设您的输入位于document变量中,请尝试以下操作:

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);
});

答案 1 :(得分:1)

您想要获取每个文档并使用其中的属性执行某些操作。听起来像是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;