是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
当前回答
简单地这么做会有什么问题吗?
someObject = {...someObject, [newKey]: someObject.oldKey}
delete someObject.oldKey
如果愿意,可以将其包装在函数中:
const renameObjectKey = (object, oldKey, newKey) => {
// if keys are the same, do nothing
if (oldKey === newKey) return;
// if old key doesn't exist, do nothing (alternatively, throw an error)
if (!object.oldKey) return;
// if new key already exists on object, do nothing (again - alternatively, throw an error)
if (object.newKey !== undefined) return;
object = { ...object, [newKey]: object[oldKey] };
delete object[oldKey];
return { ...object };
};
// in use
let myObject = {
keyOne: 'abc',
keyTwo: 123
};
// avoids mutating original
let renamed = renameObjectKey(myObject, 'keyTwo', 'renamedKey');
console.log(myObject, renamed);
// myObject
/* {
"keyOne": "abc",
"keyTwo": 123,
} */
// renamed
/* {
"keyOne": "abc",
"renamedKey": 123,
} */
其他回答
function iterate(instance) {
for (let child of instance.tree_down) iterate(child);
instance.children = instance.tree_down;
delete instance.tree_down;
}
iterate(link_hierarchy);
console.log(link_hierarchy);
就我个人而言,重命名对象中的键而不实现额外的沉重插件和轮子的最有效的方法:
var str = JSON.stringify(object);
str = str.replace(/oldKey/g, 'newKey');
str = str.replace(/oldKey2/g, 'newKey2');
object = JSON.parse(str);
如果对象具有无效的结构,还可以将其封装在try-catch中。工作完美无缺:)
如果有人需要重命名object的键:
const renameKeyObject = (obj, oldKey, newKey) => { 如果 (旧键 === 新键) 返回 volj; Object.keys(obj).forEach((key) => { if (key === oldKey) { obj[newKey] = obj[key]; 删除 obj[键]; } else if (obj[key] !== null &&; typeof obj[key] === “object”) { obj[key] = renameKeyObject(obj[key], oldKey, newKey); } }); 返回卷; };
还有一种最强大的REDUCE方法。
数据= {\ key1:“value1”,key2:“value2”,key3:“value3”}; 键文件夹= {\ key1:“firstkey”,key2:“secondkey”,key3:“thirdkey” mappedData = Object.keys . .还原((obj,k) =>对象。assign(obj, {\ [keyMap]]:数据[k]},{\}; 控制台日志(mappedData); 第一个“value1”、“secondkey”、“value2”、“thirdkey”、“value3”……
如果你不想改变你的数据,考虑这个函数…
renameProp = (oldProp, newProp, { [oldProp]: old, ...others }) => ({
[newProp]: old,
...others
})
Yazeed Bzadough的详细解释 https://medium.com/front-end-hacking/immutably-rename-object-keys-in-javascript-5f6353c7b6dd
下面是一个typescript友好的版本:
// These generics are inferred, do not pass them in.
export const renameKey = <
OldKey extends keyof T,
NewKey extends string,
T extends Record<string, unknown>
>(
oldKey: OldKey,
newKey: NewKey extends keyof T ? never : NewKey,
userObject: T
): Record<NewKey, T[OldKey]> & Omit<T, OldKey> => {
const { [oldKey]: value, ...common } = userObject
return {
...common,
...({ [newKey]: value } as Record<NewKey, T[OldKey]>)
}
}
它将防止您破坏现有的键或将其重命名为相同的东西