是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
当前回答
我认为最完整(和正确)的方法是:
if (old_key !== new_key) {
Object.defineProperty(o, new_key,
Object.getOwnPropertyDescriptor(o, old_key));
delete o[old_key];
}
此方法确保重命名的属性的行为与原始属性相同。
另外,在我看来,把它包装成一个函数/方法,并把它放入对象的可能性。原型与你的问题无关。
其他回答
您可以尝试lodash _mapkeys。
Var用户= { 名称:“安德鲁”, id: 25日 报道:假 }; Var重命名= _。mapKeys(用户,函数(值,键){ 返回键+ "_" + user.id; }); console.log(重命名); < script src = " https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js " > < /脚本>
我只想用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"}
如果有人需要重命名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); } }); 返回卷; };
这是我对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,
} */