Express.js 如何在响应中省略虚假字段

问题描述 投票:0回答:1

在express中,我如何省略json响应中的空或假字段?

我的快递应用程序:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.json({
      msg: "OK",
      error: null,
    })
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

响应是

{ msg: 'OK', error: null }
,而我希望错误不应该存在,因为它是空的。
我尝试使用 app.send() 或 app.json(),它们返回相同的值。

node.js json express
1个回答
0
投票

您可以使用

Object.entries
Object.fromEntries
从对象中删除 null 或未定义的值。

app.get('/', (req, res) => {
    const data = {
      msg: "OK",
      error: null,
    };
    const filtered = Object.entries(data).filter(([k, v]) => v);
    const result = Object.fromEntries(filtered);
    res.json(result);
});
© www.soinside.com 2019 - 2024. All rights reserved.