2012-04-10 33 views
2

使用下列的函數:移除的前緣和後在對象鍵空間和值

// 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; 
} 

除去前緣和在值尾部空格是沒有問題的。我知道你不能重命名鍵,但是我很難達到我以後的輸出。

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

這沒有達到預期的輸出。

任何想法?最好是創建一個新對象,然後銷燬原始對象?那個語法看起來像什麼?數據

例子:

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}]; 
+0

這有什麼好做JSON和[有作爲JSON對象沒有這樣的事情(http://benalman.com/news/2010/03/theres-no-such-thing-作爲一種JSON /)。另外,jQuery已經證明['.trim()'](http://api.jquery.com/jQuery.trim/)方法,所以使用它來代替滾動你自己的方法。你能否提供一個'data'的例子,以便我們更好地理解問題是什麼? – 2012-04-10 18:50:31

+0

謝謝。提供示例 – S16 2012-04-10 18:55:31

回答

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]; 
     } 
    }); 
}); 

演示:http://jsfiddle.net/mattball/ZLcGg/

0

也許我遲到了這個討論,但我想與大家分享從這個鏈接這個問題和答案。這個解決方案不僅處理上面介紹的這個對象,而且遞歸地修剪JavaScript對象中的鍵和值(字符串類型)。

希望這會有所幫助。

Trim white spaces in both Object key and value recursively