简体   繁体   中英

How to filter this array based on an array of object within an array of object

I`ve been stucked in this problem for a few hours already. Suppose my lead object has a matched_listings field and the match listings field has a listing.contact_details array of object with an email field inside, I need to filter my leads data based on the listing_contact_details array of object, basically return all leads that matches the email within the listing_contact_details of the matched_listings and the email variable i got from req.query. I tried implementation from using sets, filter, map, includes method but i cant seem to get it. Would appreciate some help:)

const getLeads = async (req, res, next) => {
  const email = req.query.email;

  let leads;
  try {
    leads = await Lead.find().populate({
      path: "matched_listings",
      match: { "listing_contact_details.email": email },
    });
  } catch (err) {
    const error = new HttpError("Something went wrong", 500);
    return next(error);
  }

  let matchedLeads;
  //filter logic
  res.json({ response: 'success'});
}; 

//Sample data set:

leads = [
  {
    matched_listings: [
      {
        listingName: "sample name",
        listing_contact_details: [
          {
            email: "email-sample@gmail.com",
            name: "sample name of contact detail",
          },
        ],
      },

      {
        listingName: "sample name2",
        listing_contact_details: [
          {
            email: "email-sample@gmail.com",
            name: "sample name of contact detail",
          },
        ],
      },
    ],

    leadName: "sample name",
    leadField: "sample field",
  },

  {
    matched_listings: [
      {
        listingName: "sample name",
        listing_contact_details: [
          {
            email: "sample-2@gmail.com",
            name: "sample name of contact detail",
          },
        ],
      },

      {
        listingName: "sample name2",
        listing_contact_details: [
          {
            email: "sample-2@gmail.com",
            name: "sample name of contact detail",
          },
        ],
      },
    ],

    leadName: "sample name 2",
    leadField: "sample field 2",
  },
];

If you wan to filter based on a single email you can try this:

leads = await Lead.find({
"matched_listings.listing_contact_details.email": email
});

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