简体   繁体   English

如何返回对象而不是数组?

[英]How can I return an object instead of an array?

I was trying to return a JSON Object but instead it returns an array.我试图返回一个 JSON 对象,但它返回一个数组。 I am using primary key for query so I am sure I will only get one result.我使用主键进行查询,所以我确信我只会得到一个结果。

This is my approach :这是我的方法:

router.get("/student_info/:id", (req, res, next) => {
    connection.getConnection((error, currentConnection) => {
        if (!!error) {
            console.log("Error occurred while connecting db")
        } else {
            let id = req.params.id;
            currentConnection.query("SELECT * FROM students WHERE id=" + "'" + id + "'", (error, rows, fields) => {
                if (!!error) {
                    console.log(error.message)
                } else {
                    res.status(200).json(rows);
                }
                currentConnection.release();
            });
        }
    });
});

What I want is this :我想要的是这个:

    {
        "id": "171-15-8966",
        "name": "Alif Hasnain",
        "course_code": "CSE412,CSE413"
    }

But I get the result like this :但我得到这样的结果:

[
    {
        "id": "171-15-8966",
        "name": "Alif Hasnain",
        "course_code": "CSE412,CSE413"
    }
]

只需在 json 转换之前获取数组的第一个元素:

res.status(200).json(rows[0]);

By default query return the array of rows reflected by the select query.默认情况下,查询返回选择查询所反映的行数组。 Since your query has single result it returns as array of single object to user.由于您的查询具有单个结果,因此它作为单个对象的数组返回给用户。

You can change it to您可以将其更改为

res.status(200).json(rows[0]);

Please let us know if got better alternate.如果有更好的替代品,请告诉我们。

Try this, using nested array destructuring试试这个,使用嵌套数组解构

res.status(200).json([[rows]]);

You can read this blog to learn more about ES6 - Destructuring您可以阅读此博客以了解有关 ES6 - 解构的更多信息

ES6 - Understanding Destructuring ES6 - 理解解构

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

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