Reputation: 4450
The Problem
I've been trying to figure out how to sort my local storage object by its keys which are milliseconds.
Example Code
// function that saves to local storage
function saveObjectToLocalStorage(key, object) {
object = JSON.stringify(object);
window.localStorage.setItem(key, object);
}
// function that gets from local storage
function getObjectFromLocalStorage(key) {
var saved = window.localStorage.getItem(key);
if (saved) {
return JSON.parse(saved);
} else {
return null;
}
}
// custom function to get milliseconds since epoch
var getId = getMillis();
// retrieve the existing object from local storage
var fruitEntry = getObjectFromLocalStorage('fruitHistory');
// then add to it
fruitEntry[getId] = {
fruit: 'banana',
weight: '100',
};
// and save it back
saveObjectToLocalStorage('fruitHistory', fruitEntry);
So local storage now looks like this
fruitHistory "{
"1111111111111":{"fruit":"banana","weight":"100"},
"1333333333333":{"fruit":"papaya","weight":"300"},
"1222222222222":{"fruit":"tomato","weight":"200"}
}"
What I Want To Do
Now I want to be able to sort these entries based on their key (id/milliseconds) so that I can save them in order of date and later output them in a reverse chronological order.
What I've Tried
I'm so far unable to modify basic examples to work for my nested key storage style.
Unable to modify Jeremy's answer to repack my object and save it back to local storage. This is one thing I've tried so far using his ES5 examples..
// get my local storage object
var fruitHistory = getObjectFromLocalStorage('fruitHistory');
// create an empty array to add to?
var keysToSort = [];
// is this converting my object to an array? or just extracting the keys to be sorted?
for (var key in fruitHistory) {
//
if (fruitHistory.hasOwnProperty(key)) {
// i have to learn more about push but does this translate just the key to the array, or does it pair the values with the keys?
keysToSort.push(key);
}
}
// this seems to sort the keys just fine
keysToSort.sort(); // Sort as strings.
// this console logging works fine at showing the above sort worked
// i don't understand how it re-pairs the values with the keys
// my attempts at re-upping the object to local storage have saved only the keys with no values attached
// so i havent been able to figure out how to rebuild it back to an object..
// ..so i can re-rup it to local storage
for (var i = 0; i < keysToSort.length; i++) {
console.log(fruitHistory[keysToSort[i]]);
}
Upvotes: 0
Views: 168
Reputation: 4450
Based on Jeremy's answer for sorting here's what I came up with to resave the sorted information to local storage after sorting.
// get our local storage info as object
var fruitObject = getObjectFromLocalStorage('fruitHistory');
// create an array
var keysToSort = [];
// convert object to array? or just adding keys without values?
for (var key in fruitObject) {
if (fruitObject.hasOwnProperty(key)) {
keysToSort.push(key);
} // end if
} // end for
// sort keys (root keys of each entry which are milliseconds based on entry date)
// so we're sorting numerically
keysToSort.sort();
// create a temporary container to output info to
$('body').append('<div class="resave-tester-container"></div>');
// output each object value to holding container (as ordered by sort)
for (var i = 0; i < keysToSort.length; i++) {
$('.resave-tester-container').append(
'<div class="fruit-entry resave-tester-item" id="' + (fruitObject[keysToSort[i]].id) + '">' +
'<div class="id">' + (fruitObject[keysToSort[i]].id) +'</div>' +
'<div class="date">' + (fruitObject[keysToSort[i]].date) +'</div>' +
'<div class="fruit">' + (fruitObject[keysToSort[i]].fruit) + '</div>' +
'<div class="weight">' + (fruitObject[keysToSort[i]].weight) + '</div>' +
'</div>'
);
} // end for
// delete current local storage object (we will rebuild it based on new dom order)
window.localStorage.removeItem('fruitHistory');
// recreate object
var rebuiltHistory = {};
// name it and save it to local storage
saveObjectToLocalStorage('fruitHistory', rebuiltHistory);
// recall it
var rebuiltHistory = getObjectFromLocalStorage('fruitHistory');
$('.resave-tester-item').each(function(index) {
// create variables based on current element
var getId = $(this).attr('id');
var getDate = $(this).find('.date').html();
var getFruit = $(this).find('.fruit').html();
var getWeight = $(this).find('.weight').html();
// add to object
rebuiltHistory[getId] = {
id: getId,
date: getDate,
fruit: getFruit,
weight: getWeight,
};
// save each object item until loop complete
saveObjectToLocalStorage('fruitHistory', rebuiltHistory);
});
/* remove temporary holding container */
$('.resave-tester-container').remove();
Here's an example fiddle
https://jsfiddle.net/Hastig/acve955m/
Upvotes: 0
Reputation: 23863
Object keys are never in a specific order, so you can't sort what you have exactly.
What you need to do is first extract the keys, then sort those.
var fruitHistory = {
"1111111111111": {
"fruit": "banana",
"weight": "100"
},
"1333333333333": {
"fruit": "papaya",
"weight": "300"
},
"1222222222222": {
"fruit": "tomato",
"weight": "200"
}
};
// ES6
var keys6 = Object.keys(fruitHistory);
// ES5
var keys5 = [];
for (var key in fruitHistory) {
if (fruitHistory.hasOwnProperty(key)) {
keys5.push(key);
}
}
console.log(keys5);
console.log(keys6);
// Once you have the keys, you can proceed either way.
keys5.sort(); // Sort as strings.
// ES5
for (var i = 0; i < keys5.length; i++) {
console.log(fruitHistory[keys5[i]]);
}
// ES6
keys6.forEach((key) => {
console.log(fruitHistory[key]);
});
Upvotes: 1