0

Right now my output renders on the page in the same order reflected in the raw JSON file. I'm hoping to figure out how to sort by a property in each item.

Examples would include sorting alphabetically by name desc and asc - or - by index asc or desc.

Any help would be much appreciated!

menu.json

{ "menuItems": [
 {
    "index": 12432564,
    "parentCategory": "Espresso",
    "name": "Caffè Americano",
    "photos": {
      "squarePhoto": "photo.jpg"
    }
  }, {
    "index": 3546754,
    "parentCategory": "Espresso",
    "name": "Caffè Latte",
    "photos": {
      "squarePhoto": "photo.jpg"
    }
  }...

master.js

$.getJSON('menu.json', function(drinks) {
  var output = "";
  for (var i in drinks.menuItems) {
      output += "<li>" + drinks.menuItems[i].name + "</li>";
  }
  //output+="</ul>";
  document.getElementById("demo").innerHTML=output;
});
Jeremy P. Beasley
  • 679
  • 1
  • 7
  • 22
  • The linked duplicate has [an answer](http://stackoverflow.com/a/979325/615754) that shows how to sort an array of objects by any property, ascending or descending. – nnnnnn Jun 06 '16 at 03:40

1 Answers1

0

You can use .sort method to sort this json object by it's name.

Hope this snippet will be useful

var o={ "menuItems": [
    {
    "index": 12432564,
    "parentCategory": "Espresso",
    "name": "Caffè Latte",
    "photos": {
      "squarePhoto": "photo.jpg"
    }
  }, {
    "index": 3546754,
    "parentCategory": "Espresso",
    "name": "Caffè Americano",
    "photos": {
      "squarePhoto": "photo.jpg"
    }
  }
]
}
var _getMenuItem  = o.menuItems;
var _sortedArray = _getMenuItem.sort(function(a,b){
  return a.name >b.name ?1 :-1
})
  console.log(_sortedArray);

jsfiddle

brk
  • 48,835
  • 10
  • 56
  • 78
  • Note that `_sortedArray` is a reference to *the same array* as `o.menuItems` and `_getMenuItem` - `.sort()` doesn't create a new array. – nnnnnn Jun 06 '16 at 03:36
  • Absolutely right , I used just elaborate the steps for easy understanding – brk Jun 06 '16 at 03:38