Q:

How to trim string values recursively from a serializable JavaScript object? 

I have a serializable JavaScript object such as 
{
  a: 'hello ',
  b: [],
  c: 5,
  d: {
    e: '  world ';
  },
}

and I would like to create a JavaScript object similar to the original object except that every string value has leading and trailing whitespace removed:
{
  a: 'hello',
  b: [],
  c: 5,
  d: {
    e: 'world';
  },
}

How can I do this? 

A:

JSON.stringify has a replacer parameter that we can use
const replacer = (key, value) => {
    if (typeof value === 'string') {
        return value.trim();
    }
    return value;
};

const trimmedObj = JSON.parse(JSON.stringify(obj, replacer));

Note that JSON does not have undefined values, so any keys with undefined values will be stripped out of the resulting object.  You may use null in place of undefined if you wish to preserve these values and if null is suitable for your purposes. 
const replacer = (key, value) => {
    if (typeof value === 'string') {
        return value.trim();
    }
    if (value === undefined) {
        // JSON doesn't have undefined
        return null;
    }
    return value;
};

