Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort JSON by value [duplicate]

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.

like image 413
diank Avatar asked Feb 23 '16 11:02

diank


2 Answers

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>');
like image 78
Nina Scholz Avatar answered Oct 21 '22 05:10

Nina Scholz


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);
like image 17
dorado Avatar answered Oct 21 '22 03:10

dorado