Javascript 如何使用下划线将数组或对象推入一个数组?
我基本上在mongo中使用$all操作符,我得到的输入可能是数组或单个元素,如下所示。那么,如何使用下划线将所有元素放在一个数组中,然后Javascript 如何使用下划线将数组或对象推入一个数组?,javascript,underscore.js,Javascript,Underscore.js,我基本上在mongo中使用$all操作符,我得到的输入可能是数组或单个元素,如下所示。那么,如何使用下划线将所有元素放在一个数组中,然后 userId = 'a'; userIds = ['a', 'b', 'c']; otherId = ['a'] or 'a'; searchArray = [userId, userIds, otherId] db.collections.find({userIds: {$all: searchArray}}) 只要是数组,就可以使用联合 _.union(
userId = 'a';
userIds = ['a', 'b', 'c'];
otherId = ['a'] or 'a';
searchArray = [userId, userIds, otherId]
db.collections.find({userIds: {$all: searchArray}})
只要是数组,就可以使用联合
_.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)
即使其中一个不是数组,而是一个数字或字符串,这也会起作用。此处的工作示例:
如果不保证所有变量都是数组,那么您可能需要
展平
方法
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}})