尝试用Javascript对json中的项目进行排序

时间:2023-01-19 19:19:29

I have a JSON string that I parse to a JSON Object with the json2.js library.

我有一个JSON字符串,我用json2解析为一个JSON对象。js库。

var parsed = JSON.parse(jsonstring);

Afterwards I do some magic to show that data to the user. The contained data are several messages. In all browsers they are sorted in the correct order. However in IE9 the order is reversed. From old messages to new messages instead of the new messages first.

然后我做了一些魔术,向用户显示数据。所包含的数据是几条消息。在所有浏览器中,它们都按照正确的顺序排序。但是在IE9中,顺序颠倒了。从旧消息到新消息,而不是新消息。

I read that the order of the parsing result is not fixed and depends on the JavaScript version. So I tried to sort the items the way I want, but it's not working.

我读到解析结果的顺序不是固定的,依赖于JavaScript版本。所以我试着按我想要的方式来分类,但它不起作用。

I currently do:

我现在做的事:

var parsed = JSON.parse(feeds);
parsed = sortJSON(parsed, "created");

function sortJSON(data, key) {
     return data.sort(function(a, b) {
            var x = a[key]; var y = b[key];
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        });
}

But I get the following error in the console:

但是我在控制台得到以下错误:

Object doesn't support property or method 'sort'

对象不支持属性或方法'sort'

So my guess is that my sorting method isn't correct because of the structure of the JSON object. So the question is 'What do I need to alter in my sort method so that it works?

我的猜测是,由于JSON对象的结构,我的排序方法不正确。所以问题是'我需要在排序方法中修改什么才能让它工作?

Structure of my json string:

我的json字符串的结构:

 {"<ID>":{"text":"...","user":"...","created":"<date>",
 "subject":"","url":"...","img_class":".."},

 "<ID>":{"text":"...","user":"...","created":"<date>","subject":"",
 "url":"...","img_class":"..."}, <MORE MESSAGES> 
 }

2 个解决方案

#1


0  

sort only works on Arrays and since your object is a hash, you could do something like this instead:

排序只适用于数组,因为对象是散列,所以可以这样做:

var items = [];
for (var k in data) {
    items.push({
        id: k,
        original: data[k]
    });
}
items.sort(...);

#2


0  

OnlyArray could be sorted, not Object. You are not guaranteed to receive back an ordered object when you sort it.

只有数组可以被排序,而不是对象。当您对一个有序对象进行排序时,您不能保证收到它。

Look at this answer for a working solution Sorting JavaScript Object by property value

请查看此答案,以获得按属性值排序JavaScript对象的有效解决方案

#1


0  

sort only works on Arrays and since your object is a hash, you could do something like this instead:

排序只适用于数组,因为对象是散列,所以可以这样做:

var items = [];
for (var k in data) {
    items.push({
        id: k,
        original: data[k]
    });
}
items.sort(...);

#2


0  

OnlyArray could be sorted, not Object. You are not guaranteed to receive back an ordered object when you sort it.

只有数组可以被排序,而不是对象。当您对一个有序对象进行排序时,您不能保证收到它。

Look at this answer for a working solution Sorting JavaScript Object by property value

请查看此答案,以获得按属性值排序JavaScript对象的有效解决方案