如果我在主体中有数组,我如何过滤结果

chhkpiq4  于 2022-10-22  发布在  Go
关注(0)|答案(2)|浏览(118)

我有一个有效载荷

{
    "category": "Mobile",
    "price": {
        "from": "10",
        "to": "50"
    },
    "location": [
        "Jakrta",
        "Bandung",
        "Surabaya"
    ],
    "rating": [
        "1",
        "2",
        "3"
    ]
}

我想找到所有的对象,有评级1或2或3,也有任何位置,基本上我是创建一个电子商务商店的过滤器,我们将获得多个位置和多个评级,所以我们将只返回那些有匹配的属性对象。我附上了一个更好的了解用户界面截图。i want to run this filter with multiple location and multiple checked checkbox

dwthyt8l

dwthyt8l1#

您可以动态创建筛选器:

const { category, price, location, rating } = req.body;

const filter = {};

if (category) filter.category = category;
if (price) filter.price = { $gte: parseInt(price.from, 10), $lte: parseInt(price.to, 10) };
if (location?.length) filter.location = { $in: location };
if (rating?.length) filter.rating = { $in: rating };

const data = await Collection.find(filter);
vddsk6oq

vddsk6oq2#

如果要过滤对象,应使用数组中的Filter():

const arr = [{
    "category": "Mobile1",
    "price": {
        "from": "10",
        "to": "50"
    },
    "location": [
        "Jakrta",
        "Bandung",
        "Surabaya"
    ],
    "rating": [
        "1",
        "2",
        "3"
    ]
},
            {
    "category": "Mobile2",
    "price": {
        "from": "10",
        "to": "50"
    },
    "location": [
        "Jakrta",
        "Bandung",
        "Surabaya"
    ],
    "rating": [
        "2",
        "3"
    ]
}];

const result = arr.filter(el => el.rating.includes("1") || el.rating.includes("2") || el.rating.includes("3"));

console.log(result);

相关问题