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

标签 javascript arrays node.js

我在我的一个 Controller 中有一个函数,我在其中填充对文档的引用数组,当填充时,它本身具有嵌入式数组。

这是一个例子:

mongoose 填充函数为我提供了一个对象数组。在每个对象中都有一个数组:

[{ name: Test, array: [ 1, 2, 3, 4, 5 ] }, { name: TestAgain, array: [1, 2, 3, 4, 5] }, { name: 测试^3 , 数组: [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).
});

最佳答案

假设您的输入在 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);
});

关于javascript - 在 Javascript/NodeJS 中连接未知数量的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31442032/

相关文章:

c++ - 下面的 C++ 代码是做什么的

node.js - 实时查询 MongoDB 文档

javascript - 如何正确地将源映射上传到具有客户端和服务器部分的项目的 Sentry ?

node.js - 在 Node 中创建 Mongoose 模型的新实例 - 将第一项添加到其中一个嵌入数组

javascript - Cordova - 下载图像并将其 move 到另一个文件夹中

Javascript:对象不支持 onclick ="status()"的此操作错误

c - 使用memset来防止 ''可变大小的对象可能无法初始化'

JavaScript : How to delete array if we have a collection of element's properties

javascript - jQuery .closest() 不选择最近的元素

javascript - 从 html 字典属性中获取所有值