JavaScript:对象重命名键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4647817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: Object Rename Key
提问by Jean Vincent
Is there a clever (i.e. optimized) way to rename a key in a javascript object?
是否有一种聪明的(即优化的)方法来重命名 javascript 对象中的键?
A non-optimized way would be:
一个非优化的方式是:
o[ new_key ] = o[ old_key ];
delete o[ old_key ];
回答by Valeriu Palo?
The most complete (and correct) way of doing this would be, I believe:
我相信,最完整(和正确)的方法是:
if (old_key !== new_key) {
Object.defineProperty(o, new_key,
Object.getOwnPropertyDescriptor(o, old_key));
delete o[old_key];
}
This method ensures that the renamed property behaves identicallyto the original one.
此方法可确保重命名的属性与原始属性的行为相同。
Also, it seems to me that the possibility to wrap this into a function/method and put it into Object.prototype
is irrelevant regarding your question.
此外,在我看来,将其包装成函数/方法并将其放入Object.prototype
与您的问题无关。
回答by ChaosPandion
You could wrap the work in a function and assign it to the Object
prototype. Maybe use the fluent interface style to make multiple renames flow.
您可以将工作包装在一个函数中并将其分配给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
ECMAScript 5 特定
I wish the syntax wasn't this complex but it is definitely nice having more control.
我希望语法不是那么复杂,但拥有更多控制权绝对是件好事。
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;
}
}
);
回答by nverba
If you're mutating your source object, ES6 can do it in one line.
如果您要修改源对象,ES6 可以在一行中完成。
delete Object.assign(o, {[newKey]: o[oldKey] })[oldKey];
Or two lines if you want to create a new object.
如果你想创建一个新对象,或者两行。
const newObject = {};
delete Object.assign(newObject, o, {[newKey]: o[oldKey] })[oldKey];
回答by pomber
In case someone needs to rename a list of properties:
如果有人需要重命名属性列表:
function renameKeys(obj, newKeys) {
const keyValues = Object.keys(obj).map(key => {
const newKey = newKeys[key] || key;
return { [newKey]: obj[key] };
});
return Object.assign({}, ...keyValues);
}
Usage:
用法:
const obj = { a: "1", b: "2" };
const newKeys = { a: "A", c: "C" };
const renamedObj = renameKeys(obj, newKeys);
console.log(renamedObj);
// {A:"1", b:"2"}
回答by xgqfrms-gildata
I would like just using the ES6(ES2015)
way!
我只想用的ES6(ES2015)
方式!
we need keeping up with the times!
我们需要与时俱进!
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"}
回答by Mulhoon
If you don't want to mutate your data, consider this function...
如果您不想改变数据,请考虑使用此功能...
renameProp = (oldProp, newProp, {[oldProp]:old, ...others}) => ({
[newProp]: old,
...others
})
A thorough explanation by Yazeed Bzadough https://medium.com/front-end-hacking/immutably-rename-object-keys-in-javascript-5f6353c7b6dd
Yazeed Bzadough 的详尽解释 https://medium.com/front-end-hacking/immutably-rename-object-keys-in-javascript-5f6353c7b6dd
回答by afalak
Most of the answers here fail to maintain JS Object key-value pairs order. If you have a form of object key-value pairs on the screen that you want to modify, for example, it is important to preserve the order of object entries.
这里的大多数答案都无法维护 JS 对象键值对的顺序。例如,如果您要修改屏幕上的某种形式的对象键值对,那么保留对象条目的顺序很重要。
The ES6 way of looping through the JS object and replacing key-value pair with the new pair with a modified key name would be something like:
ES6 循环遍历 JS 对象并将键值对替换为带有修改过的键名的新对的方法类似于:
let newWordsObject = {};
Object.keys(oldObject).forEach(key => {
if (key === oldKey) {
let newPair = { [newKey]: oldObject[oldKey] };
newWordsObject = { ...newWordsObject, ...newPair }
} else {
newWordsObject = { ...newWordsObject, [key]: oldObject[key] }
}
});
The solution preserves the order of entries by adding the new entry in the place of the old one.
该解决方案通过在旧条目的位置添加新条目来保留条目的顺序。
回答by Penny Liu
You can try lodash _.mapKeys
.
你可以试试 lodash _.mapKeys
。
var user = {
name: "Andrew",
id: 25,
reported: false
};
var renamed = _.mapKeys(user, function(value, key) {
return key + "_" + user.id;
});
console.log(renamed);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
回答by Jeff Lowery
A variation using object destructuring and spread operator:
使用对象解构和扩展运算符的变体:
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};
回答by Novitoll
Personally, the most effective way to rename keys in object without implementing extra heavy plugins and wheels:
就个人而言,在不实现额外繁重的插件和轮子的情况下重命名对象中键的最有效方法:
var str = JSON.stringify(object);
str = str.replace(/oldKey/g, 'newKey');
str = str.replace(/oldKey2/g, 'newKey2');
object = JSON.parse(str);
You can also wrap it in try-catch
if your object has invalid structure. Works perfectly :)
try-catch
如果您的对象具有无效结构,您也可以将其包装起来。完美运行:)