简体   繁体   English

按字母顺序排序 JSON

[英]Sort JSON alphabetically

I have a JSON object generated based on data stored in a table.我有一个 JSON object 是根据存储在表中的数据生成的。 I then need to be able to sort it in different ways, but when I do JSON.stringify(array) and try to sort from there it doesn't work.然后我需要能够以不同的方式对它进行排序,但是当我执行JSON.stringify(array)并尝试从那里进行排序时,它不起作用。 When I try to just do array.sort();当我尝试只做array.sort(); it will change the order, but ultimately doesn't work.它会改变顺序,但最终不起作用。 I don't have much experience with JSON and how to operate it so I'm not sure what else to try.我对 JSON 以及如何操作它没有太多经验,所以我不确定还能尝试什么。 After sorting it I need to go through and rewrite the table with the selected category in alphabetical order.排序后,我需要通过 go 并按字母顺序用所选类别重写表格。

The JSON looks like this: JSON 看起来像这样:

var arr = [{
"Functional Category":"T-Shirt",
"Brand Name":"threadless",
"When Obtained":"Last 3 Months",
"How Obtained":"Purchased",
"How Often Worn":"Monthly",
"Where It's Made":"India",
"Has a Graphic":"Yes"}]

I have a fiddle setup here: http://jsfiddle.net/Skooljester/88HVZ/1/ and I have tried what was suggested here but was unable to make it work.我在这里有一个小提琴设置: http://jsfiddle.net/Skooljester/88HVZ/1/我已经尝试了这里的建议但无法使其工作。

I have two questions, one: how do I go about accomplishing this, and two: is there a better way to do the sorting?我有两个问题,一个:我 go 如何完成此任务,第二个:是否有更好的排序方法?

see below code .... 见下面的代码....

function sortObject(o) {
    var sorted = {},
    key, a = [];

    for (key in o) {
        if (o.hasOwnProperty(key)) {
                a.push(key);
        }
    }

    a.sort();

    for (key = 0; key < a.length; key++) {
        sorted[a[key]] = o[a[key]];
    }
    return sorted;
}

Does that help? 这有帮助吗?

First, define a compare function: 首先,定义一个比较函数:

function compare(el1, el2, index) {
  return el1[index] == el2[index] ? 0 : (el1[index] < el2[index] ? -1 : 1);
}

Then, to sort the array on the first column, use this: 然后,要对第一列上的数组进行排序,请使用:

array.sort(function(el1,el2){
  return compare(el1, el2, "Functional Category")
});

Or, to sort on the first column AZ, and on the second column ZA if the first column is equal: 或者,对第一列AZ进行排序,如果第一列相等,则对第二列ZA进行排序:

array.sort(function(el1,el2){
  var compared = compare(el1, el2, "Functional Category")
  return compared == 0 ? -compare(el1, el2, "Brand Name") : compared;
});

The Mozilla developer documentation has a helpful explanation of the sort function. Mozilla开发人员文档对sort函数有一个有用的解释。 You can provide a function as a parameter that tells the browser how to do the sort. 您可以提供一个函数作为参数,告诉浏览器如何进行排序。

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

Some pseudo-code from that link, with the myArray.sort call added and the function name removed: 来自该链接的一些伪代码,添加了myArray.sort调用并删除了函数名称:

myArray.sort(function(a, b) {
  if (a is less than b by some ordering criterion)
     return -1;
  if (a is greater than b by the ordering criterion)
     return 1;
  // a must be equal to b
  return 0;
});

EDIT: It looks like you have a single-element array with an object as the element. 编辑:看起来你有一个单元素数组,对象作为元素。 Objects are unordered. 物体是无序的。 You have to transform it to an array before it can be sorted. 在对数组进行排序之前,必须将其转换为数组。 Try this (with the Object.keys and Array.prototype.map functions added via augment.js for older browsers): 试试这个(通过augment.js为旧浏览器添加Object.keys和Array.prototype.map函数):

var result = Object.keys(myArray[0]).sort().map(function(key) {
    return [key,myArray[0][key]];
});

This will give you a sorted, nested array of the form: 这将为您提供一个排序的,嵌套的表单数组:

[["Brand Name","threadless"],
 ["Function Category","T-Shirt"],
 ...
]

Something of this kind might be on help: 这种东西可能会有所帮助:

function (obj) {
   var a = [],x;
   for(x in obj){ 
     if(obj.hasOwnProperty(x)){
         a.push([x,obj[x]]);
     }
   }
   a.sort(function(a,b){ return a[0]>b[0]?1:-1; })
   return a;
}

If your intent is to allow the user to sort the table dynamically, then my approach may be slightly different. 如果您的目的是允许用户动态地对表进行排序,那么我的方法可能会略有不同。

There are plenty of jQuery table sorting plugins. 有很多jQuery表排序插件。 I have had good success with this one: http://tablesorter.com/docs/ 我在这个方面取得了很大的成功: http//tablesorter.com/docs/

Allows multi-column sort, a default sort, wire up to events, etc... etc... 允许多列排序,默认排序,连接事件等...等...

This way you can build your table as you already are, and sorting can be done secondary even before page output. 通过这种方式,您可以按原样构建表,并且即使在页输出之前也可以进行二次排序。

You can use this approach too.您也可以使用这种方法。 Used less variable to save few lines here!!在这里使用较少的变量来节省几行! 😉 😉

var newArr = [{}]; // just to matching pattern with Que variable here
Object.keys(arr[0]).sort().forEach(s => {
    newArr[0][s] = arr[0][s];
})

console.log(newArr);

This might be helpful for someone in the future if you want to do deep sorting for json properties (where a property value is also a Json object)如果您想对 json 属性(其中属性值也是 Json 对象)进行深度排序,这可能对将来的某人有帮助

function sortObject(o) {
    var sorted = {},
    key, a = [];

    for (key in o) {
        if (o.hasOwnProperty(key)) {
                a.push(key);
        }
    }

    a.sort();

    for (key = 0; key < a.length; key++) {
        if(typeof o[a[key]] === 'object'){
            sorted[a[key]] = sortObject(o[a[key]]);
        } else{
            sorted[a[key]] = o[a[key]];
        }
        
    }
    return sorted;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM