删除对象键和值中的前导和尾随空格

使用以下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; } 

删除值中的前导和尾随空格不是问题。 我知道你不能重命名键,但我很难实现我之后的输出。

 $.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}]; 

 $.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/

也许我迟到了这个讨论,但我想分享这个问题和这个链接的答案。 该解决方案不仅处理上面提到的这个对象,而且还递归地修剪JavaScript对象中的键和值(字符串类型)。

希望这会有所帮助。

递归修剪Object键和值中的空格