Trim white spaces in both Object key and value recursively

后端 未结 8 1962
一生所求
一生所求 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:12

    @RobG Thank you for the solution. Adding one more condition will not create more nested objects

    function trimObj(obj) {
          if (obj === null && !Array.isArray(obj) && typeof obj != 'object') return obj;
          return Object.keys(obj).reduce(function(acc, key) { 
            acc[key.trim()] = typeof obj[key] === 'string' ? 
              obj[key].trim() : typeof obj[key] === 'object' ?  trimObj(obj[key]) : obj[key];
            return acc;
          }, Array.isArray(obj)? []:{});
        }
    

提交回复
热议问题