按字母顺序按首字母排序JSON

时间:2017-05-03 03:28:14

标签: javascript laravel-5 vuejs2

我有一个像这样的JSON:

[
  {
    "id": 1,
    "slug": "abakan",
    "name": "Абакан"
  },
  {
    "id": 4,
    "slug": "almetevsk",
    "name": "Альметьевск"
  },
  {
    "id": 10,
    "slug": "astrahan",
    "name": "Астрахань"
  },
  {
    "id": 11,
    "slug": "barnaul",
    "name": "Барнаул"
  },
  ...
]

通过这种方法得到这个:

public function getCities()
{
    $cities = City::mainCities()->get(['id', 'slug', 'name']);
    return response()->json($cities);
}

我如何按字母顺序和字母对此列表进行排序。例如:

"A": [
  {
    "id": 1,
    "slug": "abakan",
    "name": "Абакан"
  },
  {
    "id": 4,
    "slug": "almetevsk",
    "name": "Альметьевск"
  }
],
"B": [
  {
    "id": 11,
    "slug": "barnaul",
    "name": "Барнаул"
  },
  ...
]

依旧......

我在后端有Laravel,前面有VueJS。

2 个答案:

答案 0 :(得分:3)

我的解决方案:

var cities = [
    {
        "id": 1,
        "slug": "abakan",
        "name": "Абакан"
    },
    {
        "id": 4,
        "slug": "almetevsk",
        "name": "Альметьевск"
    },
    {
        "id": 11,
        "slug": "barnaul",
        "name": "Барнаул"
    },
    {
        "id": 10,
        "slug": "astrahan",
        "name": "Астрахань"
    }
];

cities.sort(function (a, b) {
    return a.slug[0].toUpperCase() > b.slug[0].toUpperCase();
});

var newCities = {};

for (var i = 0; i < cities.length; i++) {
    var c = cities[i].slug[0].toUpperCase();
    if (newCities[c] && newCities[c].length >= 0)
        newCities[c].push(cities[i]);
    else {
        newCities[c] = [];
        newCities[c].push(cities[i]);
    }
}

console.log(newCities);

答案 1 :(得分:0)

这对我有用:

fName = "C:\\LOCAL\\FILE_" + "[" + m + "]" + "[" + y + "]" + ".xls";