Q:

Response.json not showing fields with value undefined

Response.json not showing fields with value undefined
I'm implementing a node api to manipulate data in a Mongo database. Queries are giving me the right JSON. When I send that JSON to a React client, fields that contain undefined are not showing up. What am I doing wrong? Is there a work-around?
To narrow the scope of my problem, add the code below to a node server. The console.log will print the right output. It will for example include status: undefined, however, the res.json will not include any nodes with a value undefined.
app.get("/test", function(req, res) {
    let test = {
        document: "test",
        data: {
            products: [
                {
                    id: 123,
                    type: "smartphone",
            name: "Motorola Moto G",
                    instock: true,
                    status: undefined,
                    link: null
                },
                {
                    id: 456,
                    type: "notsosmartphone",
            name: "Samsung S7",
                    instock: false,
                    status: "burning",
                    link: undefined
                }
            ],
            length: 2,
            date_created: '20161015T09:15',
            status: undefined,
            person: {name: "Kathy", age: 30, cute: true},
            arr:[123,"abc",{"a":"1"},{"b":"2"},{"c":"3"}]
        }
    };
    console.log(test);
    res.json(test);
});

A:

Expressjs response.json() method uses JS JSON.stringify() method to convert object to a JSON string.
JSON.stringify() explicitly removes undefined values from objects whenever it is called as undefined is not a valid JSON value type.
You can use a replacer function to explicitly override the undefined behavior and set values to null instead, so that they are returned on your response.
Example:
app.set('json replacer', function (key, value) {
    // undefined values are set to `null`
    if (typeof value === "undefined") {
      return null;
    }
    return value;
  }
);

