因此,关于如何遍历对象并简单地更改属性名称,有很多问题,但是我要解决的问题有些棘手,将不胜感激。
基本上,我想制作一个像这样的对象:
{
home_number: '1234',
customer: {
name: {
last_name: 'Smith',
},
},
};
变成这个
{
home_number: '1234',
individual: {
name: {
lastName: 'Smith',
},
},
};
此刻,我的功能如下
function restructure(obj) {
let newObj = {};
const newKeys = {
fed_tax_id: 'federalTaxId',
company_structure: 'companyStructure',
home_number: 'homeNumber',
customer: 'individual',
first_name: 'firstName',
last_name: 'lastName',
}
}
for(let key in obj){
if (typeof obj[key] === 'object') {
restructure(obj[key])
}
if(Object.hasOwnProperty.call(newKeys, key)){
let newProperty = newKeys[key]
newObj[newProperty] = obj[key]
}
if(!Object.hasOwnProperty.call(newKeys, key)){
newObj[key] = obj[key]
}
return newObj;
}
此刻我正在苦苦挣扎的一件事是删除需要更改的键(我创建了newKeys对象,以显示需要更改的键以及需要更改的键的方式。 )。即在这种情况下,当客户更改为个人时,也会将“ last_name”更改为“ lastName”。
通过我目前的功能,该对象以如下方式返回:
{ homeNumber: '1234' }
谢谢:)如果已经问过这个问题,请让我知道,但是在整个地方搜索之后,我找不到一个足够接近这个问题的问题。
由于restructure
返回了新对象,因此您需要分配递归调用restructure
的结果,否则它将不被使用,这就是当前代码中发生的事情。
但是映射条目数组可能会更容易-将条目中的键替换为对象上的关联值if该对象具有该键,然后将条目转换为带有[ C0]:
Object.fromEntries
请记住,const newKeys = {
fed_tax_id: 'federalTaxId',
company_structure: 'companyStructure',
home_number: 'homeNumber',
customer: 'individual',
first_name: 'firstName',
last_name: 'lastName',
};
const restructure = obj => Object.fromEntries(
Object.entries(obj).map(
([key, val]) => [
newKeys[key] || key,
typeof val === 'object' && val !== null ? restructure(val) : val
]
)
);
console.log(restructure({
home_number: '1234',
customer: {
name: {
last_name: 'Smith',
},
},
}));
给出了typeof null
,因此您需要在递归重组之前检查object
(如上面的代码所述,否则可能偶尔会出错)。>>
您可以使用null
从对象中删除属性。
您只需要检查自己的属性和实际对象,以防止分配不自己的属性。
您可以使用function restructure(obj) {
let newObj = {};
const newKeys = { fed_tax_id: 'federalTaxId', company_structure: 'companyStructure', home_number: 'homeNumber', customer: 'individual', first_name: 'firstName', last_name: 'lastName' };
for (let key in obj) {
if (!obj.hasOwnProperty(key)) continue;
newObj[newKeys[key] || key] = obj[key] && typeof obj[key] === 'object'
? restructure(obj[key])
: obj[key];
}
return newObj;
}
console.log(restructure({ home_number: '1234', customer: { name: { last_name: 'Smith' } } }));
和Object.entries