Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 533
mark Avatar asked Mar 22 '26 06:03

mark


1 Answers

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;
};
like image 159
mark Avatar answered Mar 23 '26 19:03

mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!