Search code examples
node.jsjsonexpress

Express.js how to omit falsy fields in response


In express, how can i omit empty or falsy fields in json response?

My express app:

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}`)
})

The response is { msg: 'OK', error: null } while i want error should not exists because it's null.
I tried using app.send() or app.json() and they return the same.


Solution

  • You can use Object.entries and Object.fromEntries to remove null or undefined values from an object.

    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);
    });