是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
当前回答
使用对象解构和展开运算符的变体:
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}
其他回答
您可以将工作包装在一个函数中,并将其分配给Object原型。也许可以使用流畅的界面样式使多个重命名流动。
Object.prototype.renameProperty = function (oldName, newName) {
// Do nothing if the names are the same
if (oldName === newName) {
return this;
}
// Check for the old property name to avoid a ReferenceError in strict mode.
if (this.hasOwnProperty(oldName)) {
this[newName] = this[oldName];
delete this[oldName];
}
return this;
};
ECMAScript 5 Specific
我希望语法不是这么复杂,但它肯定是很好的有更多的控制。
Object.defineProperty(
Object.prototype,
'renameProperty',
{
writable : false, // Cannot alter this property
enumerable : false, // Will not show up in a for-in loop.
configurable : false, // Cannot be deleted via the delete operator
value : function (oldName, newName) {
// Do nothing if the names are the same
if (oldName === newName) {
return this;
}
// Check for the old property name to
// avoid a ReferenceError in strict mode.
if (this.hasOwnProperty(oldName)) {
this[newName] = this[oldName];
delete this[oldName];
}
return this;
}
}
);
我只想用ES6(ES2015)的方式!
我们需要跟上时代!
const old_obj = { k1: `111`, k2: `222`, k3: `333` }; console.log(`old_obj =\n`, old_obj); // {k1: "111", k2: "222", k3: "333"} /** * @author xgqfrms * @description ES6 ...spread & Destructuring Assignment */ const { k1: kA, k2: kB, k3: kC, } = {...old_obj} console.log(`kA = ${kA},`, `kB = ${kB},`, `kC = ${kC}\n`); // kA = 111, kB = 222, kC = 333 const new_obj = Object.assign( {}, { kA, kB, kC } ); console.log(`new_obj =\n`, new_obj); // {kA: "111", kB: "222", kC: "333"}
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);
这是我对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);
如果你不想改变你的数据,考虑这个函数…
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]>)
}
}
它将防止您破坏现有的键或将其重命名为相同的东西