是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
是否有一个聪明的(即优化)方法重命名一个关键在javascript对象?
一种非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
当前回答
如果你要改变源对象,ES6可以在一行中完成。
delete Object.assign(o, {[newKey]: o[oldKey] })[oldKey];
如果你想创建一个新对象,可以用两行。
const newObject = {};
delete Object.assign(newObject, o, {[newKey]: o[oldKey] })[oldKey];
其他回答
您可以使用实用程序来处理这个问题。
npm i paix
import { paix } from 'paix';
const source_object = { FirstName: "Jhon", LastName: "Doe", Ignored: true };
const replacement = { FirstName: 'first_name', LastName: 'last_name' };
const modified_object = paix(source_object, replacement);
console.log(modified_object);
// { Ignored: true, first_name: 'Jhon', last_name: 'Doe' };
我会这样做:
function renameKeys(dict, keyMap) {
return _.reduce(dict, function(newDict, val, oldKey) {
var newKey = keyMap[oldKey] || oldKey
newDict[newKey] = val
return newDict
}, {})
}
如果你想保持对象的相同顺序
changeObjectKeyName(objectToChange, oldKeyName: string, newKeyName: string){
const otherKeys = cloneDeep(objectToChange);
delete otherKeys[oldKeyName];
const changedKey = objectToChange[oldKeyName];
return {...{[newKeyName] : changedKey} , ...otherKeys};
}
使用方法:
changeObjectKeyName ( {'a' : 1}, 'a', 'A');
这是我对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);
如果有人需要重命名属性列表:
function renameKeys(obj, newKeys) {
const keyValues = Object.keys(obj).map(key => {
const newKey = newKeys[key] || key;
return { [newKey]: obj[key] };
});
return Object.assign({}, ...keyValues);
}
用法:
const obj = { a: "1", b: "2" };
const newKeys = { a: "A", c: "C" };
const renamedObj = renameKeys(obj, newKeys);
console.log(renamedObj);
// {A:"1", b:"2"}