Skip to content

How to order localStorage by KEY ASC?

I save data to localStorage.
To be able to order the localStorage i use milliseconds as key.
(But localStorage doesn’t sort or order, so i need to build a array or object that i can sort by key)

var key = Date.now();
var value = { 
    "id": id,
    "name": name
};

//ADD DATA TO OBJECT
localStorage.setItem(key, JSON.stringify(value));

Now i’d like to fetch localStorage and display the data ordered by key asc.

I tried:

//CONSOLE LOG LOCALSTORAGE
Storage {1614866637849: "{"id":"1","name":"A"}", 1614866687890: "{"id":"3","name":"C"}", 1614866642078: "{"id":"2","name":"B"}", length: 3}

//DECLARE NEW OBJ
var items = {};
    
//LOOP THREW localStorage
Object.keys(localStorage).forEach(function(key){

    //FETCH THIS ROUND DATA
    items[key] = JSON.parse(localStorage.getItem(key));
});
 
//CONSOLE LOG ITEMS
1614866637849: {…}, 1614866687890: {…}, 1614866642078: {…}}
    
//SORT ITEMS
var sorted_items = Object.keys(items).reduce((accumulator, currentValue) => {accumulator[currentValue] = items[currentValue]; return accumulator;}, {});
    
//CONSOLE LOG SORTED ITEMS
1614866637849: {…}, 1614866687890: {…}, 1614866642078: {…}}

So it looks like my ordering function does nothing?
How can i loop out my data from localStorage by key ASC?

The order i wan’t is:
….49
….78
….90

Answer

The easiest and smartest way was commented by @Mr.polywhirl

Just add .sort() in the forEach:

Object.keys(localStorage).sort().forEach(function(key){..