0

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

Björn C
  • 3,094
  • 6
  • 33
  • 71

3 Answers3

0

If you want to just print the results in key order, just sort the keys before calling forEach.

Object.keys(localStorage).sort().forEach...

If you want sorted "pairs", because key order is not guaranteed, you can try the following.

const storage =  {
  1614866637849: '{"id":"1","name":"A"}',
  1614866687890: '{"id":"3","name":"C"}',
  1614866642078: '{"id":"2","name":"B"}'
};

const pairs = Object.entries(storage)
  .map(([key, value]) => ({
    key: parseInt(key),
    value: JSON.parse(value)
  }))
  .sort(({ key: keyA }, { key: keyB }) => keyA - keyB);
  
console.log(pairs);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 31,606
  • 11
  • 65
  • 114
0

You can do it this way:

Object.entries(YOUROBJECT).sort().reduce( (o,[k,v]) => (o[k]=v,o), {} );

Your example:

var yourdata = {1614866637849:{"id":"1","name":"A"}, 1614866687890:{"id":"3","name":"C"}, 1614866642078:{"id":"2","name":"B"}, length: 3};
console.log("BEFORE", yourdata);
console.log("NOW", Object.entries(yourdata).sort().reduce( (o,[k,v]) => (o[k]=v,o), {} ));

Result:

1614866637849: {id: "1", name: "A"}
1614866642078: {id: "2", name: "B"}
1614866687890: {id: "3", name: "C"}

Credit goes to: Sort JavaScript object by key @sravan ganji

Ultrazz008
  • 1,460
  • 1
  • 10
  • 25
0

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

Just add .sort() in the forEach:

Object.keys(localStorage).sort().forEach(function(key){..
Björn C
  • 3,094
  • 6
  • 33
  • 71