Javascript 更改对象键的顺序....
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6959817/
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
Changing the order of the Object keys....
提问by John Cooper
var addObjectResponse = [{
'DateTimeTaken': '/Date(1301494335000-0400)/',
'Weight': 100909.090909091,
'Height': 182.88,
'SPO2': '222.00000',
'BloodPressureSystolic': 120,
'BloodPressureDiastolic': 80,
'BloodPressurePosition': 'Standing',
'VitalSite': 'Popliteal',
'Laterality': 'Right',
'CuffSize': 'XL',
'HeartRate': 111,
'HeartRateRegularity': 'Regular',
'Resprate': 111,
'Temperature': 36.6666666666667,
'TemperatureMethod': 'Oral',
'HeadCircumference': '',
}];
This is a sample object which i am getting from back end, now i want to change the order of the object. I don't want to sort by name or size... i just want to manually change the order...
这是我从后端获取的示例对象,现在我想更改对象的顺序。我不想按名称或大小排序...我只想手动更改顺序...
采纳答案by Chamika Sandamal
if you want to manually reorder. simply create new object and assign values using old object.
如果您想手动重新排序。只需创建新对象并使用旧对象分配值。
var newObject= [{
'DateTimeTaken': addObjectResponse.DateTimeTaken,
'Weight': addObjectResponse.Weight,
'Height': addObjectResponse.Height,
'SPO2': addObjectResponse.SPO2
}];
回答by jontsai
You can't order JavaScript object key/value pairs. It's stored in its own internal format, so you should never rely on the order of that. In JS, everything is an Object, even an Array. So sometimes you can introduce bugs when using array notation and object notation together (for x in var
)
您不能订购 JavaScript 对象键/值对。它以它自己的内部格式存储,所以你永远不应该依赖它的顺序。在 JS 中,一切都是对象,甚至是数组。所以有时你会在同时使用数组表示法和对象表示法时引入错误 ( for x in var
)
回答by Ben K.
I wrote this small algorithm which allows to move keys, it's like jQuery .insertAfter()
method. You have to provide:
我写了这个允许移动键的小算法,它就像 jQuery.insertAfter()
方法。您必须提供:
//currentKey: the key you want to move
//afterKey: position to move-after the currentKey, null or '' if it must be in position [0]
//obj: object
function moveObjectElement(currentKey, afterKey, obj) {
var result = {};
var val = obj[currentKey];
delete obj[currentKey];
var next = -1;
var i = 0;
if(typeof afterKey == 'undefined' || afterKey == null) afterKey = '';
$.each(obj, function(k, v) {
if((afterKey == '' && i == 0) || next == 1) {
result[currentKey] = val;
next = 0;
}
if(k == afterKey) { next = 1; }
result[k] = v;
++i;
});
if(next == 1) {
result[currentKey] = val;
}
if(next !== -1) return result; else return obj;
}
Example:
例子:
var el = {a: 1, b: 3, c:8, d:2 }
el = moveObjectElement('d', '', el); // {d,a,b,c}
el = moveObjectElement('b', 'd', el); // {d,b,a,c}
回答by Tim Down
Properties of an object in JavaScript do not have an order. There may appear to be an order in some browsers but the ECMAScript specification defines object property enumeration order as being implementation-specific so you should not assume one browser's behaviour will be the same as another's. Chrome, for example, does not use the same ordering as some other browsers: see this lengthy bug reportfor at least as much discussion of this issue as you could possibly want.
JavaScript 中对象的属性没有顺序。在某些浏览器中似乎有一个顺序,但 ECMAScript 规范将对象属性枚举顺序定义为特定于实现的,因此您不应假设一个浏览器的行为与另一个浏览器的行为相同。例如,Chrome 不使用与其他一些浏览器相同的顺序:请参阅这个冗长的错误报告,至少尽可能多地讨论这个问题。
If you need a specific order, use an array, or two arrays (one for keys and one for values).
如果您需要特定顺序,请使用一个数组或两个数组(一个用于键,一个用于值)。
回答by vardump
You can use Object.keys():
您可以使用 Object.keys():
var obj = {
a: 1,
b: 2,
c: 4
};
var new_obj = {};
Object.keys(obj)
.sort(function(a, b) {
/** Insert your custom sorting function here */
return a - b;
})
.forEach(function(key) {
new_obj[key] = obj[key];
});
obj = new_obj;
回答by Jeff Vdovjak
If you create a new object from the first object (as the current accepted answer suggests) you will always need to know all of the properties in your object (a maintenance nightmare).
如果您从第一个对象创建一个新对象(正如当前接受的答案所暗示的那样),您将始终需要知道对象中的所有属性(维护噩梦)。
Use Object.assign()
instead.
使用Object.assign()
来代替。
*This works in modern browsers -- not in IE or Edge <12.
*这适用于现代浏览器——不适用于 IE 或 Edge <12。
let addObjectResponse = {
'DateTimeTaken': '/Date(1301494335000-0400)/',
'Weight': 100909.090909091,
'Height': 182.88,
'SPO2': '222.00000',
'BloodPressureSystolic': 120,
'BloodPressureDiastolic': 80,
'BloodPressurePosition': 'Standing',
'VitalSite': 'Popliteal',
'Laterality': 'Right',
'CuffSize': 'XL',
'HeartRate': 111,
'HeartRateRegularity': 'Regular',
'Resprate': 111,
'Temperature': 36.6666666666667,
'TemperatureMethod': 'Oral',
'HeadCircumference': '',
};
// Create an object which will serve as the order template
let objectOrder = {
'HeartRate': null,
'HeartRateRegularity': null,
}
addObjectResource = Object.assign(objectOrder, addObjectResource);
Now the two items you wanted ordered are in order, and the remaining properties are below them.
现在您要订购的两个项目已按顺序排列,其余属性在它们下方。
Now your object will look like this:
现在您的对象将如下所示:
{
'HeartRate': 111,
'HeartRateRegularity': 'Regular',
'DateTimeTaken': '/Date(1301494335000-0400)/',
'Weight': 100909.090909091,
'Height': 182.88,
'SPO2': '222.00000',
'BloodPressureSystolic': 120,
'BloodPressureDiastolic': 80,
'BloodPressurePosition': 'Standing',
'VitalSite': 'Popliteal',
'Laterality': 'Right',
'CuffSize': 'XL',
'Resprate': 111,
'Temperature': 36.6666666666667,
'TemperatureMethod': 'Oral',
'HeadCircumference': '',
}
回答by u3999328
If you do not want to create a new object, you can use the following code snippet.
如果不想创建新对象,可以使用以下代码片段。
function orderKey(obj, keyOrder) {
keyOrder.forEach((k) => {
const v = obj[k]
delete obj[k]
obj[k] = v
})
}
here is a codepen: https://codepen.io/zhangyanwei/pen/QJeRxB
这是一个代码笔:https://codepen.io/zhangyanwei/pen/QJeRxB
回答by Cmndo
I like the approved answer by Chamika Sandamal. Here's a simple function that uses their same logic with a little be of freedom to change the order as you need it.
我喜欢 Chamika Sandamal 批准的答案。这是一个简单的函数,它使用相同的逻辑,并可以根据需要随意更改顺序。
function preferredOrder(obj, order) {
var newObject = {};
for(var i = 0; i < order.length; i++) {
if(obj.hasOwnProperty(order[i])) {
newObject[order[i]] = obj[order[i]];
}
}
return newObject;
}
You give it an object, and an array of the key names you want, and returns a new object of those properties arranged in that order.
你给它一个对象和一个你想要的键名的数组,然后返回一个按该顺序排列的属性的新对象。
var data = {
c: 50,
a: 25,
d: 10,
b: 30
};
data = preferredOrder(data, [
"a",
"b",
"c",
"d"
]);
console.log(data);
/*
data = {
a: 25,
b: 30,
c: 50,
d: 10
}
*/
I'm copying and pasting from a big JSON object into a CMS and a little bit of re-organizing of the source JSON into the same order as the fields in the CMS has saved my sanity.
我正在将一个大的 JSON 对象复制并粘贴到 CMS 中,并将源 JSON 稍微重新组织为与 CMS 中的字段相同的顺序,这使我保持理智。
回答by KARASZI István
I think that's not possible in JavaScript.
我认为这在 JavaScript 中是不可能的。
You can create an array which will contain the field names in your order and you can iterate through this array and fetch the fields from the actual object.
您可以创建一个数组,该数组将包含您订单中的字段名称,您可以遍历该数组并从实际对象中获取字段。
回答by silverstrike
Just refer to the object keys in the order that you like:
只需按照您喜欢的顺序引用对象键:
aKeys = [
addObjectResponse[0].DateTimeTaken,
addObjectResponse[0].Weight,
addObjectResponse[0].Height,
...etc...
]