I am tying read a json file by looping through the topmenu (array of objects) and get item out it and store it into localstorage. everything works fine and even the data gets stored in localstorage. But my problem is it stores the data in localStorage in a sorted order which might be its default behavior. But I dont need it in sorted order, I want it in the order which it is present in the json. Because when I store the data to localstorage and read the data from localstorage it comes in the sorted order. I can use the key in the $.each and append it to maintain our order if it automatically sorts. But why is it sorting itself. Is there any other work-around. Please help me solving this.
NOTE:
I need to store the data to localStorage from json. Then read it from localstorage and donot read the json till the localstorage is completely empty. When I manually change the values in localstorage it should reflect in the menu. I have done all the conditional coding just need to figure out the localstorage problem, which is storing it in sorting order.
Below is my JSON file, javascript and partial html:
JSON
{
"topmenu":
[
{
"item": "File"
},
{
"item": "Help"
},
{
"item": "Edit"
},
{
"item": "View"
},
{
"item": "Go"
},
{
"item": "Tools"
},
{
"item": "Actions"
}
]
}
JAVASCRIPT
<script>
$(function() {
if (typeof localStorage === "undefined") {
alert("Sorry, your browser does not support web storage...");
}
$.getJSON("header.json", function(data) {
$.each(data.topmenu, function(key, val) {
localStorage.setItem(val.item, val.item);
});
loadMenu();
});
function loadMenu() {
$('.horizontalmenu').html('');
if (!localStorage.length < 1) {
for (var i = 0; i < localStorage.length; i++) {
var item = localStorage.getItem(localStorage.key(i));
$('.horizontalmenu').append('<li class="menu"><a href="#">' + item + '</a></li>');
}
} else {
$('.horizontalmenu').html("<li class='menu'>No menu</li>");
}
}
});
</script>
PARTIAL HTML
<div id="header">
<div id="header-title">
Test
</div>
<div id="header-menu">
<ul class="horizontalmenu">
</ul>
</div>
</div>