Javascript 重命名对象中的键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6942137/
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
Rename the keys in an object
提问by John Cooper
var addObjectResponse = [{
'SPO2': '222.00000',
'VitalGroupID': 1152,
'Temperature': 36.6666666666667,
'DateTimeTaken': '/Date(1301494335000-0400)/',
'UserID': 1,
'Height': 182.88,
'UserName': 'Admin',
'BloodPressureDiastolic': 80,
'Weight': 100909.090909091,
'TemperatureMethod': 'Oral',
'Resprate': 111,
'HeartRate': 111,
'BloodPressurePosition': 'Standing',
'VitalSite': 'Popliteal',
'VitalID': 1135,
'Laterality': 'Right',
'HeartRateRegularity': 'Regular',
'HeadCircumference': '',
'BloodPressureSystolic': 120,
'CuffSize': 'XL',
}];
How to rename the keys... like SPO2 into O2... there are such many objects in the array...
如何重命名键...就像SPO2变成O2...数组中有这么多对象...
回答by Ilia Choly
maybe something like this?
也许是这样的?
var i, len = addObjectResponse.length;
for (i = 0; i < len; i++) {
addObjectResponse[i]['O2'] = addObjectResponse[i]['SPO2'];
delete addObjectResponse[i]['SPO2'];
}
or
或者
addObjectResponse = addObjectResponse.map(function (obj) {
obj['O2'] = obj['SP02'];
delete obj['S02'];
return obj;
});
or
或者
for (let obj of addObjectResponse) {
obj['O2'] = obj['SP02'];
delete obj['S02'];
}
or
或者
function renameProperty(obj, fromKey, toKey) {
obj[toKey] = obj[fromKey];
delete obj[fromKey];
}
addObjectResponse.forEach(obj => renameProperty(obj, 'SP02', 'O2'));
回答by Jon
You cannot directly rename the properties. However, you can set new properties and unset the old ones, indirectly "renaming" them:
您不能直接重命名属性。但是,您可以设置新属性并取消设置旧属性,间接“重命名”它们:
function rename(obj, oldName, newName) {
if(!obj.hasOwnProperty(oldName)) {
return false;
}
obj[newName] = obj[oldName];
delete obj[oldName];
return true;
}
回答by rsp
Immutable key renaming in vanilla JS one-liner
vanilla JS one-liner 中的不可变键重命名
This may not be the most efficient way to rename a key but I think it's interesting in certain ways:
这可能不是重命名键的最有效方法,但我认为它在某些方面很有趣:
- It doesn't mutate the original objects
- It takes one line of vanilla JavaScript
- It demonstrates the use of modern syntax
- 它不会改变原始对象
- 它需要一行原生 JavaScript
- 它演示了现代语法的使用
No.1 may sometimes be needed if you still need to use the original array. No.2 may be interesting considering the fact that some of the examples here have more than 30 lines of code. No.3 may serve an educational purpose to demostrate some of the features of the language that are not used as often as they should, considering the fact how powerful and how widely supported they are.
如果您仍然需要使用原始数组,有时可能需要 No.1。考虑到这里的一些示例有 30 多行代码,No.2 可能会很有趣。No.3 可能用于教育目的,以展示该语言的一些不常使用的功能,考虑到它们的强大和广泛支持的事实。
If you create a mapping object like this:
如果您创建这样的映射对象:
const m = { SPO2: 'O2' };
then you'll be able to add more keys to rename in the future easily.
那么您将能够添加更多密钥以在将来轻松重命名。
Now, can create a one-liner in vanilla JS:
现在,可以在 vanilla JS 中创建一个单行:
const t = o => Object.assign(...Object.keys(o).map(k => ({ [m[k] || k]: o[k] })));
Let's say that you have an array of objects:
假设您有一个对象数组:
const a = [{
'SPO2': '222.00000',
'VitalGroupID': 1152,
}, {
'SPO2': '333.00000',
'VitalGroupID': 1153,
}, {
'SPO2': '444.00000',
'VitalGroupID': 1154,
}];
You can get a new array with a.map(t)
like this:
您可以a.map(t)
像这样获得一个新数组:
console.log('Before:', a);
console.log('After:', a.map(t));
Your original objects are still intact in the original array.
您的原始对象在原始数组中仍然完好无损。
回答by meni181818
I have created a nice function to rename properties names: https://github.com/meni181818/simpleCloneJS/blob/master/renameProperties.js
我创建了一个很好的函数来重命名属性名称:https: //github.com/meni181818/simpleCloneJS/blob/master/renameProperties.js
usage:
用法:
var renamedObj = renameProperties(sourceObject, {propName: 'propNEWname', anotherPropName: 'anotherPropNEWname'});
My function, also handles objects inside arrays so in your case you can do:
我的函数还处理数组内的对象,因此在您的情况下,您可以执行以下操作:
addObjectResponse = renameProperties(addObjectResponse, {SPO2: 'O2'});
function renameProperties(sourceObj, replaceList, destObj) {
destObj = destObj || {};
each(sourceObj, function(key) {
if(sourceObj.hasOwnProperty(key)) {
if(sourceObj[key] instanceof Array) {
if(replaceList[key]) {
var newName = replaceList[key];
destObj[newName] = [];
renameProperties(sourceObj[key], replaceList, destObj[newName]);
} else if(!replaceList[key]) {
destObj[key] = [];
renameProperties(sourceObj[key], replaceList, destObj[key]);
}
} else if(typeof sourceObj[key] === 'object') {
if(replaceList[key]) {
var newName = replaceList[key];
destObj[newName] = {};
renameProperties(sourceObj[key], replaceList, destObj[newName]);
} else if(!replaceList[key]) {
destObj[key] = {};
renameProperties(sourceObj[key], replaceList, destObj[key]);
}
} else {
if(replaceList[key]) {
var newName = replaceList[key];
destObj[newName] = sourceObj[key];
} else if(!replaceList[key]) {
destObj[key] = sourceObj[key];
}
}
}
});
return destObj;
}
on line 3 in the function above, we using each()
function. which is this:
在上面函数的第 3 行,我们使用each()
函数。这是这样的:
function each(objOrArr, callBack) {
if(objOrArr instanceof Array) {
for(var i = 0; i < objOrArr.length; i++) {
callBack(i);
}
} else if(typeof objOrArr === 'object') {
for(var prop in objOrArr) {
// if the property really exist
if(objOrArr.hasOwnProperty(prop)) {
callBack(prop);
}
}
}
}
note:If you are using Jquery OR underscore.js Or another library that has 'each()' function, you can use it Instead. just replece to $.each
(jquery) or _.each
(underscore.js).
注意:如果您使用的是 Jquery 或 underscore.js 或其他具有 'each()' 函数的库,则可以使用它来代替。只需替换$.each
(jquery) 或_.each
(underscore.js)。
回答by Molomby
Ok, so there's two things you're doing here, iterating through an array and renaming properties of an object.
好的,您在这里要做两件事,遍历数组和重命名对象的属性。
Firstly, to itterate you should generally be using the arrays map()
function.
It's less error prone than using a for ( .. )
loop and slightly nicer than forEach()
, I think.
A for ( .. )
loop will usually give you better performance (depending on the JS engine) but you need to be dealing with pretty massive array to notice (ie. maybe a ~10ms difference for 100k elements).
首先,要进行迭代,您通常应该使用 arraysmap()
函数。它比使用for ( .. )
循环更不容易出错,而且比forEach()
我认为的好一点。一个for ( .. )
循环通常会给你更好的性能(取决于JS引擎),但你需要有非常庞大的阵列来处理,以通知(即可能是为100K〜元素10ms的差异)。
Secondly, to rename a object property, the obvious solution is to just set the new key and deleting the old.
This will work but won't always give you properties that behave exactly like the old one if a custom getter or setter has been defined.
If you're creating a generic helper function to do this kind of work you'd be better off using
Object.defineProperty()
and
Object.getOwnPropertyDescriptor()
.
其次,要重命名对象属性,显而易见的解决方案是设置新键并删除旧键。如果定义了自定义 getter 或 setter,这将起作用,但不会总是为您提供与旧属性完全相同的属性。如果你正在创建一个通用的辅助函数来完成这种工作,你最好使用
Object.defineProperty()
and
Object.getOwnPropertyDescriptor()
。
Putting this together we get:
把这些放在一起,我们得到:
function renameKeyInObjArray (array, oldKey, newKey) {
return array.map(function (obj) {
Object.defineProperty(obj, newKey, Object.getOwnPropertyDescriptor(obj, oldKey));
delete obj[oldKey];
return obj;
});
}
// Use our new function to process the array
renameKeyInObjArray(addObjectResponse, 'SPO2', 'O2');
This function updates the contents of the array by reference and also returns a reference to the array, so can be chained. It's also written in ES5.1 syntax so should run pretty much everywhere.
该函数通过引用更新数组的内容并返回对数组的引用,因此可以链接。它也是用 ES5.1 语法编写的,因此几乎可以在任何地方运行。
回答by Pablo S G Pacheco
Instead of renaming this object key, you could create another object with proper names, like this:
您可以创建另一个具有适当名称的对象,而不是重命名此对象键,如下所示:
var obj={wrongKeyName:'test'};
var obj2 = {}
obj2.rightKeyName = obj.wrongKeyName;
console.log(obj2);
回答by taz
addObjectResponse[0]["O2"] = addObjectResponse[0]["SPO2"];
addObjectResponse[0]["SP02"] = null;
The [0] is necessary because addObjectResponse is set to an array with one element, which contains an object. Do you have any rules as to what keys will be renamed or how?
[0] 是必需的,因为 addObjectResponse 设置为一个包含一个元素的数组,其中包含一个对象。您对哪些键将被重命名或如何重命名有任何规则吗?
Edit: I misunderstood the OP, thinking that "many objects" referred to many keys in the object that need to be renamed, as opposed to many objects in the array that each need to have that one key renamed.
编辑:我误解了 OP,认为“许多对象”指的是对象中需要重命名的许多键,而不是数组中的许多对象,每个对象都需要重命名一个键。
回答by Alex K.
You can add + delete(read the IE caveat);
您可以添加 +删除(阅读 IE 警告);
var addObjectResponse = [{
'SPO2': '222.00000',
'VitalGroupID': 1152
}]
for (var k in addObjectResponse[0])
log(k)
>>SPO2
>>VitalGroupID
addObjectResponse[0]['O2'] = addObjectResponse[0]['SPO2']
delete addObjectResponse[0]['SPO2']
for (var k in addObjectResponse[0])
log(k)
>>VitalGroupID
>>O2