Search code examples
javascriptarraysjavascript-objectsprisma

Remap an array to have an object above each entry in javascript


I have a prisma query that returns users on a pivot table CommunityMember. The pivot table associates to the table User. As a result, my queries into the User table do not place the object user on top of the replies. I have a lot of functions designed to run with the user object on top so I am trying to figure out how to map user into my returns so the functions can run correctly. I've tried a lot of combinations of map and have had no luck. Do you all have any ideas?

Here is my prisma query:

        members = await prisma.user.findMany({
            select: {
                id: true,
                username: true,
                name: true,
                bio: true,
                avatar: true,
            },
            skip: 10 * Number(page),
            take: 10,
        });

It gives a result like

members:
 [{id: 2, username: 'man}, {id: 3, username: 'dan'}]

I want it to look like: members:

members:
[{user: {id: 2, username: 'man'}}, {user: {id: 3. username: 'dan'}}]

If I run members[0].user I should get the data inside. It seems like a simple map function, but I have not been able to get it to work.

Another example of what I get, but do not want.

members:  [
  {
      id: 2,
      username: 'man',
      name: 'A Man',
      bio: 'A man.',
      avatar: [Object]
  },
  {
      id: 3,
      username: 'dude',
      name: 'Dude',
      bio: "Dude is a #1 developer.",
      avatar: [Object]
  },

This is what I want.

members:  [
  {
    //Notice the user object on top of each entry
    user: {
      id: 2,
      username: 'man',
      name: 'A Man',
      bio: 'Man.',
      avatar: [Object]
    }
  },
  {
    user: {
      id: 3,
      username: 'dude',
      name: 'Dude',
      bio: "Dudes a #1 developer.",
      avatar: [Object]
    }
  },
]

Solution

  • Not sure I got the whole picture but wouldn't this do?

        const members = [
          {
              id: 2,
              username: 'man',
              name: 'A Man',
              bio: 'A man.',
              avatar: {}
          },
          {
              id: 3,
              username: 'dude',
              name: 'Dude',
              bio: "Dude is a #1 developer.",
              avatar: {}
          }
        ].map(member => ({user: member}))