按字母顺序对JSON排序 [英] Sort JSON alphabetically

查看:494
本文介绍了按字母顺序对JSON排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于存储在表中的数据生成的JSON对象.然后,我需要能够以不同的方式对其进行排序,但是当我执行JSON.stringify(array)并尝试从那里进行排序时,它将不起作用.当我尝试执行array.sort();时,它将更改顺序,但最终不起作用.我对JSON及其操作方法没有太多的经验,所以我不确定还有什么尝试.排序后,我需要遍历并按字母顺序用所选类别重写表.

I have a JSON object generated based on data stored in a table. 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. When I try to just do 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. After sorting it I need to go through and rewrite the table with the selected category in alphabetical order.

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"}]

我在这里设置了小提琴: http://jsfiddle.net/Skooljester/88HVZ/1 /,我尝试了在此处提出的建议,但无法使其正常工作

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.

我有两个问题,一个是:我该如何完成这项工作,另一个是:有没有更好的方法来进行排序?

I have two questions, one: how do I go about accomplishing this, and two: is there a better way to do the sorting?

推荐答案

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

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")
});

或者,如果第一列相等,则对第一列A-Z和第二列Z-A进行排序:

Or, to sort on the first column A-Z, and on the second column Z-A if the first column is equal:

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

这篇关于按字母顺序对JSON排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆