是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
当前回答
还有一种最强大的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”……
其他回答
使用对象解构和展开运算符的变体:
const old_obj = {
k1: `111`,
k2: `222`,
k3: `333`
};
// destructuring, with renaming. The variable 'rest' will hold those values not assigned to kA, kB, or kC.
const {
k1: kA,
k2: kB,
k3: kC,
...rest
} = old_obj;
// now create a new object, with the renamed properties kA, kB, kC;
// spread the remaining original properties in the 'rest' variable
const newObj = {kA, kB, kC, ...rest};
对于一个键,这可以很简单:
const { k1: kA, ...rest } = old_obj;
const new_obj = { kA, ...rest }
你也可能喜欢更“传统”的风格:
const { k1, ...rest } = old_obj
const new_obj = { kA: k1, ...rest}
我的方法,改编好的@Mulhoon typescript帖子,用于更改多个键:
const renameKeys = <
TOldKey extends keyof T,
TNewkey extends string,
T extends Record<string, unknown>
>(
keys: {[ key: string]: TNewkey extends TOldKey ? never : TNewkey },
obj: T
) => Object
.keys(obj)
.reduce((acc, key) => ({
...acc,
...{ [keys[key] || key]: obj[key] }
}), {});
renameKeys({id: 'value', name: 'label'}, {id: 'toto_id', name: 'toto', age: 35});
这是我对pomber函数做的一个小修改; 为了能够获取一个对象数组而不是单独的对象,你也可以激活索引。此外,“键”也可以由数组分配
function renameKeys(arrayObject, newKeys, index = false) {
let newArray = [];
arrayObject.forEach((obj,item)=>{
const keyValues = Object.keys(obj).map((key,i) => {
return {[newKeys[i] || key]:obj[key]}
});
let id = (index) ? {'ID':item} : {};
newArray.push(Object.assign(id, ...keyValues));
});
return newArray;
}
test
const obj = [{ a: "1", b: "2" }, { a: "5", b: "4" } ,{ a: "3", b: "0" }];
const newKeys = ["A","C"];
const renamedObj = renameKeys(obj, newKeys);
console.log(renamedObj);
简单地这么做会有什么问题吗?
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,
} */
下面是创建具有重命名键的新对象的示例。
let x = { id: "checkout", name: "git checkout", description: "checkout repository" };
let renamed = Object.entries(x).reduce((u, [n, v]) => {
u[`__${n}`] = v;
return u;
}, {});