简体   繁体   中英

Is there a way to match the _id of one mongodb array to the corresponding clientId from another array?

I have 2 arrays coming from my MongoDB database, one called users that returns a list of user objects like this:

[{
email: "poe@email.com",
firstName: "Poe",
lastName: "Damaren",
_id: "bb8"
}]

and one called treatments that has a corresponding clientId that should match the _id from one of the objects in the user array, ie:

[{
clientId: "bb8",
date: "2022-02-04",
treatment "fixed antenna",
_id: "r2d2"
}]

On my client side using React, I'm trying to show a table with a row for every treatments object where the date is greater than today, and then show a column for the date, and a column for the firstName and lastName from the user object whose _id corresponds to the clientId from the treatment object (I hope that makes sense). I've tried putting it together, but I get stuck trying to show the first and last name. This is where I'm at:

<table>
   <thead>
      <tr>
        <th>Date</th>
        <th>Name</th>
      </tr>
    </thead>
    <tbody>
      {treatments?.map((t)=>(
         new Date(t?.date) >= today ? (                  
            <tr>
              <td>{t?.date}</td>
              <td>{users?.firstName?.find(u=>u?._id === t?.clientId)}</td>
            </tr>
          ) : (
            <div></div>
          ))
        )}
    </tbody>
</table>

Is there a way to get the first name and last name to show within a table row for each element in the treatments array? Something like this:

Date Name
2022-02-04 Poe Damaren

Help me stackoverflow community, you're my only hope...

You can write a simple function to retrieve the full name.

const getFullName = t => {
    const { firstName = "", lastName = "" } = users?.find(
        u => u?._id === t?.clientId
    );
    return `${firstName} ${lastName}`;
};
<tr>
    <td>{t?.date}</td>
    <td>{getFullName(t)}</td>
</tr>

编辑 beautiful-matsumoto-89rb3

NOTE: I would attach the firstName and lastName to each treatment on the backend side to reduce computations done on the UI side. Same for filtering treatments using the date.

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