如何在本地存储中对嵌套键进行数字排序

时间:2016-10-02 06:52:48

标签: javascript arrays sorting local-storage javascript-objects

问题

我一直在试图弄清楚如何按照几毫秒的键对我的本地存储对象进行排序。

示例代码

// 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]]);
}

2 个答案:

答案 0 :(得分:1)

对象键永远不会按特定顺序排列,因此您无法对所拥有的内容进行精确排序。

您需要做的是首先提取密钥,然后对其进行排序。

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]);
});

答案 1 :(得分:0)

基于Jeremy在这里排序的答案,这是我在排序后将排序后的信息重新保存到本地存储的原因。

  // 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();

这是一个示例小提琴

https://jsfiddle.net/Hastig/acve955m/