Trim white spaces in both Object key and value recursively

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

    You can clean up the property names and attributes using Object.keys to get an array of the keys, then Array.prototype.reduce to iterate over the keys and create a new object with trimmed keys and values. The function needs to be recursive so that it also trims nested Objects and Arrays.

    Note that it only deals with plain Arrays and Objects, if you want to deal with other types of object, the call to reduce needs to be more sophisticated to determine the type of object (e.g. a suitably clever version of new obj.constructor()).

    function trimObj(obj) {
      if (!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() : trimObj(obj[key]);
        return acc;
      }, Array.isArray(obj)? []:{});
    }
    

提交回复
热议问题