3

Using the following function:

// remove multiple, leading or trailing spaces
function trim(s) {
    s = s.replace(/(^\s*)|(\s*$)/gi,"");
    s = s.replace(/[ ]{2,}/gi," ");
    s = s.replace(/\n /,"\n");
    return s;
}

removing the leading and trailing whitespaces in the value is not a problem. I know you can't rename keys, but I'm having difficulty acheiving the output I'm after.

$.each(data, function(index)
    {
        $.each(this, function(k, v)
        {
            data[index][trim(k)] = trim(v);
            data.splice(index, 1);
        });
    });

This is not achieving the desired output.

Any ideas? Would it be best to create a new object and then destroy the original? What would that syntax look like?

Example of data:

var data = [{
    "Country": "Spain",
    "info info1": 0.329235716,
    "info info2": 0.447683684,
    "info info3": 0.447683747},
{
    " Country ": " Chile ",
    "info info1": 1.302673893,
    "info info2 ": 1.357820775,
    "info info3": 1.35626442},
{
    "Country": "USA",
    "info info1  ": 7.78805016,
    "info info2": 26.59681951,
    "info info3": 9.200900779}];
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
S16
  • 2,963
  • 9
  • 40
  • 64
  • This has nothing to do with JSON, and [there's no such thing as a JSON object](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). Also jQuery already proves a [`$.trim()`](http://api.jquery.com/jQuery.trim/) method, so use that instead of rolling your own. Could you provide an example of `data` so we might better understand exactly what the problem is? – Matt Ball Apr 10 '12 at 18:50

2 Answers2

2
$.each(data, function(index) {
    var that = this;
    $.each(that, function(key, value) {
        var newKey = $.trim(key);

        if (typeof value === 'string')
        {
            that[newKey] = $.trim(value);
        }

        if (newKey !== key) {
            delete that[key];
        }
    });
});

Demo: http://jsfiddle.net/mattball/ZLcGg/

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0

Maybe I am late to this discussion but I'd like to share this question and answers from this link. This solution not only deal with this object presented above but also recursively trim keys and value(string type) in JavaScript object.

Hope this will help.

Trim white spaces in both Object key and value recursively

Community
  • 1
  • 1
vichsu
  • 1,880
  • 5
  • 17
  • 20