最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

如何通过快速js过滤动态对象

IT培训 admin 15浏览 0评论

如何通过快速js过滤动态对象

我正在使用Express for REST api,我想通过req.query对我的帖子进行一些过滤,在帖子结构中,我使用了动态对象调用选项,即我的帖子结构:

{
    "category": [
        {
            "id": 2,
            "name": "mashin"
        },
        {
            "id": 102,
            "name": "savari"
        }
    ],
    "_id": "5eb52dc8e2838431703942eb",
    "user": "5deea38cfc84f42590e01942",
    "title": "qazwsx",
    "description": "qazwsx",
    "options": {
        "price": "100"
    },
    "phone": "",
    "date": "2020-05-08T10:00:40.626Z",
    "__v": 0
},
{
    "category": [
        {
            "id": 2,
            "name": "mashin"
        },
        {
            "id": 102,
            "name": "savari"
        }
    ],
    "_id": "5eb52db6e2838431703942ea",
    "user": "5deea38cfc84f42590e01942",
    "title": "xswzaq",
    "description": "qazwsx",
    "options": {
        "transaction_type": "",
    },
    "phone": "",
    "date": "2020-05-08T10:00:22.783Z",
    "__v": 0
},

如您所见,有些帖子带有价格,而其他帖子则没有。对于后端的过滤器,我使用以下代码:

    router.get('/', async (req, res) => {
    try {
        const posts = await Post.find().sort({ date: -1 });

        let response = [];

        const q = {}  // Query object
        if (req.query.city) { q.city = req.query.city }
        if (req.query.title) { q.title = req.query.title }

        if (Object.keys(q).length === 0) {
            // NO query parameters, send it all...
            response = posts;
        } else {
            // We have a query, filter response to match request
            response = posts.filter(post => {
                return Object.keys(q).every((key) => post[key] === q[key]);
            }, q);
        }

        // Filter by Price
        if (req.query.PriceFrom) {
            response.filter(post => {
                if (typeof (post.options.price) !== 'undefined') {
                    console.log('p' + post.options)
                }
                else {
                    console.log('n' + post.options)
                }
            })
        }

        // de-duplication:
        response = _.uniqBy(response, 'id');

        const resultPosts = response.slice(req.query.start, req.query.count)
        res.json(resultPosts);

    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Error!');
    }
});

并且在console.log中,我收到此错误:

[0] { price: '100' }
[0] Cannot read property 'price' of undefined
[0] { transaction_type: '', price: '100' }
[0] { transaction_type: '200', price: '200' }
[0] { transaction_type: '1', price: '100' }

您有解决方案或想法吗?

回答如下:

问题是您尝试访问.price,其中post.options未定义。因此,添加它,它应该捕获未定义的post.options而不会引发错误。

 if (post.options && typeof (post.options.price) !== 'undefined') {}

如何通过快速js过滤动态对象

我正在使用Express for REST api,我想通过req.query对我的帖子进行一些过滤,在帖子结构中,我使用了动态对象调用选项,即我的帖子结构:

{
    "category": [
        {
            "id": 2,
            "name": "mashin"
        },
        {
            "id": 102,
            "name": "savari"
        }
    ],
    "_id": "5eb52dc8e2838431703942eb",
    "user": "5deea38cfc84f42590e01942",
    "title": "qazwsx",
    "description": "qazwsx",
    "options": {
        "price": "100"
    },
    "phone": "",
    "date": "2020-05-08T10:00:40.626Z",
    "__v": 0
},
{
    "category": [
        {
            "id": 2,
            "name": "mashin"
        },
        {
            "id": 102,
            "name": "savari"
        }
    ],
    "_id": "5eb52db6e2838431703942ea",
    "user": "5deea38cfc84f42590e01942",
    "title": "xswzaq",
    "description": "qazwsx",
    "options": {
        "transaction_type": "",
    },
    "phone": "",
    "date": "2020-05-08T10:00:22.783Z",
    "__v": 0
},

如您所见,有些帖子带有价格,而其他帖子则没有。对于后端的过滤器,我使用以下代码:

    router.get('/', async (req, res) => {
    try {
        const posts = await Post.find().sort({ date: -1 });

        let response = [];

        const q = {}  // Query object
        if (req.query.city) { q.city = req.query.city }
        if (req.query.title) { q.title = req.query.title }

        if (Object.keys(q).length === 0) {
            // NO query parameters, send it all...
            response = posts;
        } else {
            // We have a query, filter response to match request
            response = posts.filter(post => {
                return Object.keys(q).every((key) => post[key] === q[key]);
            }, q);
        }

        // Filter by Price
        if (req.query.PriceFrom) {
            response.filter(post => {
                if (typeof (post.options.price) !== 'undefined') {
                    console.log('p' + post.options)
                }
                else {
                    console.log('n' + post.options)
                }
            })
        }

        // de-duplication:
        response = _.uniqBy(response, 'id');

        const resultPosts = response.slice(req.query.start, req.query.count)
        res.json(resultPosts);

    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Error!');
    }
});

并且在console.log中,我收到此错误:

[0] { price: '100' }
[0] Cannot read property 'price' of undefined
[0] { transaction_type: '', price: '100' }
[0] { transaction_type: '200', price: '200' }
[0] { transaction_type: '1', price: '100' }

您有解决方案或想法吗?

回答如下:

问题是您尝试访问.price,其中post.options未定义。因此,添加它,它应该捕获未定义的post.options而不会引发错误。

 if (post.options && typeof (post.options.price) !== 'undefined') {}

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论