I want to load an external JSON object and sort based on one or more key:value pairs. For example using the JSON below I might need to sort on category1 and then type.
I've tried array.sort()
but no matter what I throw at it my data is never sorted; It's always output in the same order as in the JSON file.
{
"books": [
{
"sku": "{1234}",
"title": "Moby Dick",
"type": "paperback",
"category1": "fiction",
"category2": "classic",
"category3": "",
"image": "",
"ctaLabel": "Learn More"
},
{
"sku": "{5678}",
"title": "1984",
"type": "hardcover",
"category1": "fiction",
"category2": "",
"category3": "",
"image": "",
"ctaLabel": "Learn More"
},
{
"sku": "{5678}",
"title": "Another Title",
"type": "paperback",
"category1": "nonfiction",
"category2": "youngadult",
"category3": "",
"image": "",
"ctaLabel": "Learn More"
}
]
}
$(function() {
$.getJSON('books.json', function (data) {
console.log(data);
var items = data.books.map(function (item) {
return item.sku + ': ' + item.title;
});
if (items.length) {
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
$("#show-data").html(list);
}
});
});