vithu shaji
vithu shaji

Reputation: 379

concatinate nested array of object ids

There are two chat rooms and each one is having two owners which are user object IDs. i would like to concatinate both the owners into one array so that i can find details of owners other than current user

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

i am expecting something like this

owners= [ 5d6caefdbb6f2921f45caf1d, 5d6caee9bb6f2921f45caf1b, 
5d6dfcd6e3b11807944348b8, 5d6caefdbb6f2921f45caf1d]

Upvotes: 0

Views: 27

Answers (2)

Vitor Ribeiro
Vitor Ribeiro

Reputation: 115

If you want to go all es6 like with javascript (making sure you are using recent browsers) you can use the array function reduce with the array concat method. Like so:

const owners = chatrooms.reduce((acc, chatroom) => acc.concat(chatroom.owners));

Upvotes: 0

Manish
Manish

Reputation: 5213

On newer browsers and node 11, you could use the flatMap method.

Something like this would work:

chatrooms.flatMap(room => room.owners)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap

And for older version, you'd do something like this:

const owners = []
chatrooms.forEach((chatroom) => {
  chatroom.owners.forEach(owner => owners.push(owner))
})

Upvotes: 2

Related Questions