简体   繁体   中英

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

I'm basically using $all operator in mongo and the input i get might be array or single element as following. So how do use underscore to put all the elements in one array and then

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

You can use union as long as they are arrays.

_.union(arrays) 

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

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

If all variables aren't promised to be arrays, you probably want the flatten method.

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}})

No need for underscore, you can use concat:

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

var arr = userId.concat(userIds, otherId)

This will work even if one of those is not an array but just a number or string. Working example here:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM