3 回答

TA贡献1111条经验 获得超0个赞
由于restructure返回新对象,因此您需要分配递归调用的结果restructure,否则它将未被使用,这就是您当前代码中发生的情况。
但是映射条目数组可能会更容易 -如果对象具有该键,则将条目中的键替换为对象上的关联值,然后将条目转回具有以下内容的对象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 nullgive object,因此您需要null在递归重组之前进行检查(如上面的代码中所做的那样),否则您可能偶尔会遇到错误。

TA贡献1784条经验 获得超2个赞
您可以使用delete从对象中删除属性。
注意:我的函数将修改原始对象。如果您想复制对象,请确保使用JSON方法进行深层复制
const newKeys = {
fed_tax_id: 'federalTaxId',
company_structure: 'companyStructure',
home_number: 'homeNumber',
customer: 'individual',
first_name: 'firstName',
last_name: 'lastName',
}
const obj = {
home_number: '1234',
individual: {
name: {
lastName: 'Smith',
},
},
};
function restructure(obj){
for(let k in obj){
if(typeof obj[k] === "object" && !Array.isArray(obj[k])){
restructure(obj[k]);
}
if(newKeys[k]){
obj[newKeys[k]] = obj[k];
delete obj[k];
}
}
}
restructure(obj);
console.log(obj)

TA贡献1835条经验 获得超7个赞
您可以使用Object.entriesand Object.fromEntries,另外,只创建一次 newKeys 对象,而不是在每次调用函数时创建它。
const newKeys = {
fed_tax_id: 'federalTaxId',
company_structure: 'companyStructure',
home_number: 'homeNumber',
customer: 'individual',
first_name: 'firstName',
last_name: 'lastName',
}
function restructure(obj) {
let entries = Object.entries(obj).map(([key, val]) => {
val = typeof val === 'object' && !Array.isArray(val) ? restructure(val) : val
return [newKeys[key] || key, val]
});
return Object.fromEntries(entries)
}
console.log(restructure({
home_number: '1234',
customer: {
name: {
last_name: 'Smith',
},
},
}))
添加回答
举报