javascript 如何对对象的 JS 对象进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14286654/
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
How to sort a JS object of objects?
提问by jeffery_the_wind
I have built an object in PHP, used JSON_encode function and send it as a JSON string to my JS script via ajax. Then I convert it back to an object. The problem I am having is that I wanted to keep the object in the order that it was originally created in. Please see this picture of what the object looks like once I get it into JS:
我在 PHP 中构建了一个对象,使用了 JSON_encode 函数并通过 ajax 将它作为 JSON 字符串发送到我的 JS 脚本。然后我将它转换回一个对象。我遇到的问题是我想按照最初创建对象的顺序保留对象。 请看这张图片,说明我将对象放入 JS 后的样子:
When I created the object, it was sorted by the customer field alphabetically. The customer name starting with A would come first, B second, etc. As you can see, now, the first element of the object as customer starting with S. It looks like somehow it got automatically sorted by the key of the top-level object, which is an integer, so I understand why this happened.
当我创建对象时,它按客户字段的字母顺序排序。以 A 开头的客户名称将首先出现,然后是 B,等等。正如您所看到的,现在,对象的第一个元素作为以 S 开头的客户。看起来它以某种方式按顶级键自动排序对象,它是一个整数,所以我明白为什么会发生这种情况。
So i want to do is re-sort this object so that all the sub-objects are sorted by the customer
field alphabetically. Is this possible? If so, how do I do it?
所以我想做的是重新排序这个对象,以便所有子对象按customer
字段按字母顺序排序。这可能吗?如果是这样,我该怎么做?
Thanks!
谢谢!
采纳答案by David Talley
It's probably the difference between a JavaScript Object and a JavaScript Array. Objects are more like hash tables, where the keys aren't sorted in any particular order, whereas Arrays are linear collections of values.
这可能是 JavaScript 对象和 JavaScript 数组之间的区别。对象更像是哈希表,其中键没有按任何特定顺序排序,而数组是值的线性集合。
In your back end, make sure you're encoding an array, rather than an object. Check the final encoded JSON, and if your collection of objects is surrounded by {} instead of [], it's being encoded as an object instead of an array.
在你的后端,确保你编码的是一个数组,而不是一个对象。检查最终编码的 JSON,如果您的对象集合被 {} 而不是 [] 包围,则它被编码为对象而不是数组。
You may run into a problem since it looks like you're trying to access the objects by an ID number, and that's the index you want those objects to occupy in the final array, which presents another problem, because you probably don't want an array with 40,000 entries when you're only storing a small amount of values.
您可能会遇到问题,因为您似乎正在尝试通过 ID 号访问对象,而这就是您希望这些对象在最终数组中占据的索引,这会带来另一个问题,因为您可能不想要当您只存储少量值时,一个包含 40,000 个条目的数组。
If you just want to iterate through the objects, you should make sure you're encoding an array instead of an object. If you want to access the objects by specific ID, you'll probably have to sort the objects client-side (i.e. have the object from the JSON response, and then create another array and sort those objects into it, so you can have the sorted objects and still be able to access them by id).
如果您只想遍历对象,则应确保对数组而不是对象进行编码。如果您想通过特定 ID 访问对象,您可能必须在客户端对对象进行排序(即从 JSON 响应中获取对象,然后创建另一个数组并将这些对象排序到其中,这样您就可以拥有排序的对象,并且仍然可以通过 id 访问它们)。
You can find efficient sorting algorithms (or use the one below from ELCas) easily via Google.
您可以通过 Google 轻松找到高效的排序算法(或使用以下来自 ELCas 的算法)。
回答by Francisco Costa
I've changed Fabricio Matéeanswer to become more flexible and return the sorted object.
我已经更改了Fabricio Matée 的答案,使其变得更加灵活并返回已排序的对象。
function alphabetical_sort_object_of_objects(data, attr) {
var arr = [];
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
var obj = {};
obj[prop] = data[prop];
obj.tempSortName = data[prop][attr].toLowerCase();
arr.push(obj);
}
}
arr.sort(function(a, b) {
var at = a.tempSortName,
bt = b.tempSortName;
return at > bt ? 1 : ( at < bt ? -1 : 0 );
});
var result = [];
for (var i=0, l=arr.length; i<l; i++) {
var obj = arr[i];
delete obj.tempSortName;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var id = prop;
}
}
var item = obj[id];
result.push(item);
}
return result;
}
Then just call the function like this
然后像这样调用函数
your_object = alphabetical_sort_object_of_objects(your_object, 'attribute_to_sort');
回答by Fabrício Matté
Here's a generic iteration function which pushes all objects into an array and sorts them by their customer
property in a case-insensitive manner, then iterates over the sorted array:
这是一个通用迭代函数,它将所有对象推送到一个数组中,并以customer
不区分大小写的方式按其属性对它们进行排序,然后迭代已排序的数组:
function iterate(data) {
var arr = [];
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
var obj = {};
obj[prop] = data[prop];
obj.tempSortName = data[prop].customer.toLowerCase();
arr.push(obj);
}
}
arr.sort(function(a, b) {
var at = a.tempSortName,
bt = b.tempSortName;
return at > bt ? 1 : ( at < bt ? -1 : 0 );
});
for (var i = 0, l = arr.length; i < l; i++) {
var obj = arr[i];
delete obj.tempSortName;
console.log(obj);
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var id = prop; //gets the obj "index" (id?)
}
}
console.log(id);
var item = obj[id];
console.log(item.customer);
//do stuff with item
}
}
回答by Esraa Mahmmoud
sortObject(object){
if(typeof object === 'object'){
if(object instanceof Date){
return object;
}
if(object instanceof Array){
return object.map(element => this.sortObject(element));
} else {
return Object.keys(object).sort().reduce((result, key) => {
if(object[key] && object[key] !== null) {
result[key] = this.sortObject(object[key]);
}
return result;
}, {});
}
}
return object;
}
回答by El Cas
Just cycle through your data and sort it. I'm not using the most efficient sorter but the ideas is there.
只需循环浏览您的数据并对其进行排序。我没有使用最有效的分拣机,但想法就在那里。
var data = toArray(AJAX_Returned_JSON); // function to convert object to array
var sortedData = null;
for(var i=0; i<data.length - 1; i++){
var temp = data[i];
for(var j=i+1; j<data.length; j++){
if(data[j].customer < temp.customer){
temp = data[j];
}
}
sortedData.push(temp);
}