gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:21:31 28 4
gpt4 key购买 nike

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

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

我所做的是:

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

我明白了:

{ GeneralInformation:
{ 'Referral No': '123123',
Marketer: '',
Casemanager: 'Alexis Clark',
'CM Username': '',
VOC: '',
'Foreign Voluntary': '',
},
AccountName: 'CTS Health',
}

我想要的是:

{ GeneralInformation:
{ ReferralNo: '123123',
Marketer: '',
Casemanager: 'Alexis Clark',
CMUsername: '',
VOC: '',
ForeignVoluntary: '',
},
AccountName: 'CTS Health',
}

我在这里做错了什么??

最佳答案

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

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);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 使用javascript删除嵌套对象中键中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43537182/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com