删除对象键和值中的前导和尾随空格 [英] Remove leading and trailing spaces in object keys and values
本文介绍了删除对象键和值中的前导和尾随空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用以下功能:
// 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?
数据示例:
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/
这篇关于删除对象键和值中的前导和尾随空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文