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/

相关文章:

java - Jackson 中的序列化数组类型和数组

Node.js/Async - 如何避免异步回调 hell ?

javascript - Javascript Promise 如何与 setTimeOut 配合使用

javascript - 为什么我无法在 jquery 中获取该单选按钮的状态?

javascript - JQuery 淡入淡出()

php - 使用 PHP (DOM) 遍历未知的 XML 结构

javascript - Redux 操作状态对象

java - 在 Java 中使用 MySQL 的 IN 语句

node.js - Node.js 中的缓冲区是什么?

javascript - 如何在puppeteer page.evaluate中使用url模块