gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:44:31 26 4
gpt4 key购买 nike

我在我的一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com