繁体   English   中英

如何根据 object 数组中的 object 数组过滤此数组

[英]How to filter this array based on an array of object within an array of object

我已经被这个问题困了几个小时了。 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在matched_listings的listing_contact_details和我从req.query获得的email变量中。 我尝试使用集合、过滤器、map 来实现,包括方法,但我似乎无法理解。 将不胜感激一些帮助:)

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",
  },
];

如果您想基于单个 email 进行过滤,您可以尝试以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM