有两个聊天室,每个聊天室都有两个所有者,它们是用户对象ID。我想将两个所有者统一为一个数组,以便我可以找到当前用户以外的所有者的详细信息
[ { owners: [ 5d6caefdbb6f2921f45caf1d, 5d6caee9bb6f2921f45caf1b ],
_id: 5d6ccf5d55b38522a042dbb2,
createdAt: 2019-09-02T08:14:21.734Z,
updatedAt: 2019-09-02T08:14:21.734Z,
__v: 0,
id: '5d6ccf5d55b38522a042dbb2' },
{ owners: [ 5d6dfcd6e3b11807944348b8, 5d6caefdbb6f2921f45caf1d ],
_id: 5d6dfd48e3b11807944348ba,
createdAt: 2019-09-03T05:42:32.572Z,
updatedAt: 2019-09-03T05:42:32.572Z,
__v: 0,
id: '5d6dfd48e3b11807944348ba' } ]
const chatrooms = await ChatRoom.find({owners:{$all:[user._id]}})
//the above code was run to get result in problem statement
const owners = []
chatrooms.forEach((chatroom) => {
owners.push(chatroom.owners)
})
我期待这样的事情
owners= [ 5d6caefdbb6f2921f45caf1d, 5d6caee9bb6f2921f45caf1b,
5d6dfcd6e3b11807944348b8, 5d6caefdbb6f2921f45caf1d]
答案 0 :(得分:2)
在较新的浏览器和节点11上,您可以使用flatMap
方法。
类似的事情会起作用:
chatrooms.flatMap(room => room.owners)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap
对于旧版本,您将执行以下操作:
const owners = []
chatrooms.forEach((chatroom) => {
chatroom.owners.forEach(owner => owners.push(owner))
})
答案 1 :(得分:0)
如果您想像使用javascript一样使用所有es6(确保您使用的是最近的浏览器),则可以将array函数reduce与array concat方法一起使用。像这样:
const owners = chatrooms.reduce((acc, chatroom) => acc.concat(chatroom.owners));