使用javascript删除嵌套对象中的键中的空格

Sun*_*ama 6 javascript

我想替换嵌套对象中的键的空格.我有一个对象如下:

     var data = 
 { 'General Information':
             { 'Referral No': '123123',
               Marketer: '',
               Casemanager: 'Alexis Clark',
               'CM Username': '',
               VOC: '',
               'Foreign Voluntary': '',
            },
     'Account Name': 'CTS Health',
    }
Run Code Online (Sandbox Code Playgroud)

我做的是:

 for (var k in data) {
    if (k.replace(/\s/g, '') !== k) {
        data[k.replace(/\s/g, '')] = data[k];
        if (data[k] !== null && typeof data[k] === 'object') {
            for (var x in data[k]) {
                if (x.replace(/\s/g, '') !== x) {
                    data[k][x.replace(/\s/g, '')] = data[k][x];
                    delete data[k][x];
                }
            }
        }
        delete data[k];
    }
}
Run Code Online (Sandbox Code Playgroud)

我明白了:

{ GeneralInformation:
         { 'Referral No': '123123',
           Marketer: '',
           Casemanager: 'Alexis Clark',
           'CM Username': '',
           VOC: '',
           'Foreign Voluntary': '',
        },
    AccountName: 'CTS Health',
  }
Run Code Online (Sandbox Code Playgroud)

我想要的是:

{ GeneralInformation:
         { ReferralNo: '123123',
           Marketer: '',
           Casemanager: 'Alexis Clark',
           CMUsername: '',
           VOC: '',
           ForeignVoluntary: '',
        },
    AccountName: 'CTS Health',
  }
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

Nin*_*olz 5

您可以对嵌套对象使用迭代和递归方法.

function replaceKeys(object) {
    Object.keys(object).forEach(function (key) {
        var newKey = key.replace(/\s+/g, '');
        if (object[key] && typeof object[key] === 'object') {
            replaceKeys(object[key]);
        }
        if (key !== newKey) {
            object[newKey] = object[key];
            delete object[key];
        }
    });
}


var data = { 'General Information': { 'Referral No': '123123', Marketer: '', Casemanager: 'Alexis Clark', 'CM Username': '', VOC: '', 'Foreign Voluntary': '', }, 'Account Name': 'CTS Health' };

replaceKeys(data);
console.log(data);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)