按字母顺序排序JSON(按特定元素) [英] Sorting JSON (by specific element) alphabetically

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

问题描述

我有一些格式如下的JSON:

I have some JSON that is formatted like:

places =[
     {
      "city":"Los Angeles",
      "country":"USA",
     },
     {
      "city":"Boston",
      "country":"USA",
     },
     {
      "city":"Chicago",
      "country":"USA",
     },
] 

et cetera ...

et cetera...

I我试图按字母顺序排序 BY CITY ,我很难这样做。我相信我的问题的根源似乎是确定角色的顺序(与数字相对)。我试过一个简单的事情:

I am trying to sort this alphabetically BY CITY and am having trouble doing so. I believe the root of my issue seems to be determining the order of the characters (versus numbers). I've tried a simple:

    places.sort(function(a,b) {
     return(a.city) - (b.customInfo.city);
    });

但是,这个减法不知道该怎么做。有人可以帮助我吗?

yet, this subtraction doesnt know what to do. Can someone help me out?

推荐答案

不幸的是,JavaScript中没有通用的比较函数来返回合适的排序值( )。我编写了一个比较运算符的compareStrings函数,然后在sort函数中使用它。

Unfortunately there is no generic "compare" function in JavaScript to return a suitable value for sort(). I'd write a compareStrings function that uses comparison operators and then use it in the sort function.

function compareStrings(a, b) {
  // Assuming you want case-insensitive comparison
  a = a.toLowerCase();
  b = b.toLowerCase();

  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

places.sort(function(a, b) {
  return compareStrings(a.city, b.city);
})

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

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