按字母顺序排序JSON

ayy*_*yyp 8 jquery json

我有一个基于存储在表中的数据生成的JSON对象.然后我需要能够以不同的方式对它进行排序,但是当我这样做JSON.stringify(array)并尝试从那里排序它不起作用.当我尝试做array.sort();它会改变顺序,但最终不起作用.我对JSON没有太多经验以及如何操作它所以我不知道还有什么可以尝试.排序之后,我需要按字母顺序重复使用所选类别的表格.

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"}]
Run Code Online (Sandbox Code Playgroud)

我在这里有一个小提琴设置:http://jsfiddle.net/Skooljester/88HVZ/1/我已经尝试过这里建议但是无法使它工作.

我有两个问题,一个问题:如何实现这一目标,以及两个问题:是否有更好的方法进行排序?

MAN*_*NGA 7

见下面的代码....

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;
}
Run Code Online (Sandbox Code Playgroud)

这有帮助吗?


Bar*_*art 6

首先,定义一个比较函数:

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

然后,要对第一列上的数组进行排序,请使用:

array.sort(function(el1,el2){
  return compare(el1, el2, "Functional Category")
});
Run Code Online (Sandbox Code Playgroud)

或者,对第一列AZ进行排序,如果第一列相等,则对第二列ZA进行排序:

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

  • 是的,我用过你之前的jsfiddle来测试它,参见http://jsfiddle.net/88HVZ/7/ (2认同)

Roy*_*ker 5

Mozilla开发人员文档对sort函数有一个有用的解释.您可以提供一个函数作为参数,告诉浏览器如何进行排序.

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

来自该链接的一些伪代码,添加了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;
});
Run Code Online (Sandbox Code Playgroud)

编辑:看起来你有一个单元素数组,对象作为元素.物体是无序的.在对数组进行排序之前,必须将其转换为数组.试试这个(通过augment.js为旧浏览器添加Object.keys和Array.prototype.map函数):

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

这将为您提供一个排序的,嵌套的表单数组:

[["Brand Name","threadless"],
 ["Function Category","T-Shirt"],
 ...
]
Run Code Online (Sandbox Code Playgroud)