Trim white spaces in both Object key and value recursively

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

    epascarello's answer above plus some unit tests (just for me to be sure):

    function trimAllFieldsInObjectAndChildren(o: any) {
      return JSON.parse(JSON.stringify(o).replace(/"\s+|\s+"/g, '"'));
    }
    
    import * as _ from 'lodash';
    assert.true(_.isEqual(trimAllFieldsInObjectAndChildren(' bob '), 'bob'));
    assert.true(_.isEqual(trimAllFieldsInObjectAndChildren('2 '), '2'));
    assert.true(_.isEqual(trimAllFieldsInObjectAndChildren(['2 ', ' bob ']), ['2', 'bob']));
    assert.true(_.isEqual(trimAllFieldsInObjectAndChildren({'b ': ' bob '}), {'b': 'bob'}));
    assert.true(_.isEqual(trimAllFieldsInObjectAndChildren({'b ': ' bob ', 'c': 5, d: true }), {'b': 'bob', 'c': 5, d: true}));
    assert.true(_.isEqual(trimAllFieldsInObjectAndChildren({'b ': ' bob ', 'c': {' d': 'alica c c '}}), {'b': 'bob', 'c': {'d': 'alica c c'}}));
    assert.true(_.isEqual(trimAllFieldsInObjectAndChildren({'a ': ' bob ', 'b': {'c ': {'d': 'e '}}}), {'a': 'bob', 'b': {'c': {'d': 'e'}}}));
    assert.true(_.isEqual(trimAllFieldsInObjectAndChildren({'a ': ' bob ', 'b': [{'c ': {'d': 'e '}}, {' f ': ' g ' }]}), {'a': 'bob', 'b': [{'c': {'d': 'e'}}, {'f': 'g' }]}));
    

提交回复
热议问题