Trim white spaces in both Object key and value recursively

后端 未结 8 1972
一生所求
一生所求 2020-12-05 05:53

How do you trim white spaces in both the keys and values in a JavaScript Object recursively?

I came across one issue in which I was trying to \"clean\" a user suppli

8条回答
  •  悲&欢浪女
    2020-12-05 06:03

    The best solution I used is this. Check the documentation on replacer function.

    var obj = {"data": {"address": {"city": "\n \r     New York", "country": "      USA     \n\n\r"}}};
    
    var trimmed = JSON.stringify(obj, (key, value) => {
      if (typeof value === 'string') {
        return value.trim();
      }
      return value;
    });
    
    console.log(JSON.parse(trimmed));

提交回复
热议问题