简体   繁体   English

在Javascript / NodeJS中串联未知数量的数组

[英]Concatenate an unknown number of arrays in Javascript/NodeJS

I have a function in one of my controllers where I populate an array of references to a document, which, when populated, have embedded arrays themselves. 我在其中一个控制器中有一个函数,在其中填充对文档的引用数组,该引用数组在填充时本身具有嵌入式数组。

Here's an example: 这是一个例子:

The mongoose populate function gives me an array of objects. 猫鼬填充函数给了我一系列对象。 Within each of those objects is an array: 这些对象中的每一个内都有一个数组:

[{ 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]},{名称:TestAgain,数组:[1,2,3,4,5]]},{名称:Test ^ 3,数组: [1、2、3、4、5]},{...

The desired output would be: 所需的输出将是:

[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...] [1、2、3、4、5、1、2、3、4、5、1、2、3、4、5,...]

I need to concatenate all of the "arrays" within the populated references. 我需要在填充的引用中连接所有“数组”。 How can I do this without knowing how many arrays there are? 不知道有多少个数组怎么办?

For reference, here is (generally) what my function looks like: 作为参考,以下是(通常)我的函数的外观:

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

Assuming your input is in the document variable, try this: 假设您的输入在document变量中,请尝试以下操作:

var output = document.reduce(function (res, cur) {
  Array.prototype.push.apply(res, cur.array);
  return res;
}, []);

Or this: 或这个:

var output = [];
document.forEach(function(cur) {
  Array.prototype.push.apply(output, cur.array);
});

You want to take each document and do something with a property from it. 您想要获取每个文档并对其进行属性处理。 Sounds like a great use case for Array.prototype.map ! 听起来像Array.prototype.map的好用例!

map will get each document's array value and return you an array of those values. map将获取每个文档的array值,并返回这些值的数组。 But, you don't want a nested array so we simply use Array.prototype.concat to flatten it. 但是,您不希望使用嵌套数组,因此我们只需使用Array.prototype.concat将其展平。 You could also use something like lodash/underscore.js flatten method. 您也可以使用类似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; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM