如何使用下划线将数组或对象推入一个数组?

how to push array or objects into one array using underscore?

我基本上在 mongo 中使用 $all 运算符,我得到的输入可能是数组或单个元素,如下所示。那么如何使用下划线将所有元素放在一个数组中然后

userId = 'a';
userIds = ['a', 'b', 'c'];
otherId = ['a'] or 'a';
searchArray = [userId, userIds, otherId]
db.collections.find({userIds: {$all: searchArray}})

只要是数组就可以用union

_.union(arrays) 

var userId = ['a'],
    userIds = ['a', 'b', 'c'];
    otherId = ['a'],

searchArray = _.union(userId, userIds, otherId);

不需要下划线,可以用concat:

var userId = ['a'],
    userIds = ['a', 'b', 'c'],
    otherId = ['a'];

var arr = userId.concat(userIds, otherId)

即使其中之一不是数组而只是数字或字符串,这仍然有效。此处的工作示例:

http://codepen.io/anon/pen/qbNQLw

如果未承诺所有变量都是数组,您可能需要 flatten 方法。

userId = 'a'; // strings
userIds = ['a', 'b', ['c']]; // multidimensional array
otherId = ['a']; // single dimensional array
searchArray = _.flatten([userId, userIds, otherId]);
db.collections.find({userIds: {$all: searchArray}})