20

how I can sort my json file by name -> value? I want to show by asc value of tag name. Any idea how to convert my json file?

Here is how look my JSON file:

[{
    "id": "105",
    "name": "FIAT",
    "active": true,
    "parentId": "1"
}, {
    "id": "106",
    "name": "AUDI",
    "active": true,
    "parentId": "1"
}, {
    "id": "107",
    "name": "BMW",
    "active": true,
    "parentId": "1"
}, {
    "id": "109",
    "name": "RENAULT",
    "active": true,
    "parentId": "1"
}]

I will be grateful if someone help me. Thanks in advance.

diank
  • 628
  • 2
  • 11
  • 19
  • 3
    Are you trying to sort on the client side or the server side? – Joe Clay Feb 23 '16 at 11:17
  • 2
    Are you using PHP or JavaScript? – Matthijs Feb 23 '16 at 11:17
  • You should give more information; like said before, we need to know you want to do it in Php or js (eg. if you want to do it client side, you don't even have to change your JSON, and just sort your array on js with _.sort() ) – Julien Leray Feb 23 '16 at 11:21
  • Are you trying to sort the whole array of objects by the value of `name`, or are you trying to sort each individual object so that the keys show up in alphabetical order? – Mark Reed Feb 23 '16 at 11:23

2 Answers2

48

I suggest to use Array#sort()

var data = [
    { "id": "105", "name": "FIAT",    "active": true, "parentId": "1" },
    { "id": "106", "name": "AUDI",    "active": true, "parentId": "1" },
    { "id": "107", "name": "BMW",     "active": true, "parentId": "1" },
    { "id": "109", "name": "RENAULT", "active": true, "parentId": "1" }
];

data.sort(function (a, b) {
    return a.name.localeCompare(b.name);
});

document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');
Gleb Kemarsky
  • 10,160
  • 7
  • 43
  • 68
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
17

Pretty straight-forward.

var data = [
  { "id": "105", "name": "FIAT",    "active": true, "parentId": "1" },
  { "id": "106", "name": "AUDI",    "active": true, "parentId": "1" },
  { "id": "107", "name": "BMW",     "active": true, "parentId": "1" },
  { "id": "109", "name": "RENAULT", "active": true, "parentId": "1" }
];

data.sort(function(a, b) {
  return a.name > b.name;
});

console.log(data);
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
dorado
  • 1,515
  • 1
  • 15
  • 38