2 回答
TA贡献1805条经验 获得超10个赞
您需要定义函数来创建新函数key value pairs,然后object从这些函数中形成一个函数。另外,检查该值是否为object, 以递归地重命名嵌套对象 -
function renameKeys(obj) {
const keyValues = Object.entries(obj).map(([key, value]) => {
let newKey = key + "1";
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
value = renameKeys(value);
}
return [newKey, value];
});
return Object.fromEntries(keyValues);
}
test = JSON.parse(
'{"verifying_explanation": {"bus_stop": ["1234"],"elementary_school": ["1234"],"middle_school": ["1234"],"high_school": ["1234"]}}'
);
console.log(test);
data = renameKeys(test, this);
console.log(data);
TA贡献1828条经验 获得超3个赞
您无法在函数中返回新的键值对,相反,您只需向 obj 添加新键并删除旧键即可。
function renameKeys(obj, newKeys) {
Object.keys(obj).map((key) => {
let newKey = key + "1";
if (Array.isArray(obj[key]) == false) {
renameKeys(obj[key], newKeys);
}
// console.log(newKey, "]", obj[key]);
obj[newKey]=obj[key];
delete obj[key];
});
}
test = JSON.parse(
`{"verifying_explanation":
{"bus_stop":["1234"],
"elementary_school":["1234"],
"middle_school":["1234"],
"high_school":["1234"]
}
}`
);
console.log(test);
data = renameKeys(test, this);
console.log(test);
添加回答
举报