我一直在試圖找出如何通過其密鑰,其毫秒我的本地存儲對象進行排序。
示例代碼
// 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);
所以本地存儲現在看起來是這樣
fruitHistory "{
"1111111111111":{"fruit":"banana","weight":"100"},
"1333333333333":{"fruit":"papaya","weight":"300"},
"1222222222222":{"fruit":"tomato","weight":"200"}
}"
我想要做什麼,
現在我希望能夠將這些條目進行排序基於它們的密鑰(id /毫秒),以便我可以按照日期和後續輸出的順序保存它們時間順序倒序。
我已經試過
我至今無法修改basic examples爲我嵌套密鑰存儲的工作作風。
無法修改Jeremy's answer重新包裝我的對象並將其保存回本地存儲。這是一兩件事至今我試着用他的ES5的例子..
// 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]]);
}
感謝傑里米,我一直在努力整合你的答案進入我的代碼的答覆,但你可以在更新看到我的問題(在'我試過的'下)如何重建並重新保存排序後的對象到本地存儲,我有點遺憾。 –
從我的回答:'對象鍵從來沒有按照特定的順序,所以你不能按照你確切的順序排序。'你可以做的唯一事情就是當你去使用所說的對象時排序對象鍵。 –