jQuery - 本地存储排序字符串化对象顺序



我有一个对象menuItems它是JSON字符串化的(其中包含3个对象)并保存在本地存储中。它以result从服务器返回。

localStorage.setItem('menuItems', JSON.stringify(result));

menuItems中的 3 个对象是:

{
    id: "1"
    item: "Apple",
    type: "fruit"
},
{
    id: "2"
    item: "Banana",
    type: "fruit"
},
{
    id: "3"
    item: "Carrot",
    type: "vegetable"
}

我从本地存储中获取menuItms,遍历其对象,并按照与上面的顺序相同的顺序获取以下列表,这是完美的。不过,我想对它们进行排序,并将新订单重新保存到本地存储,因此在循环访问它们时,我会在数据排序 id 中输出每次迭代的索引。

<ul class="sort-menu-items-list">
    <li data-sort-id="0">Apple is a fruit</li>
    <li data-sort-id="1">Banana is a fruit</li>
    <li data-sort-id="2">Carrot is a vegetable</li>
</ul>

在前端对它们进行排序后,我得到以下作为最终排序顺序。我想将对象menuItems重新保存在本地存储中,以便始终按以下新顺序检索它们:

<ul class="sort-menu-items-list">
    <li data-sort-id="2">Carrot is a vegetable</li>
    <li data-sort-id="0">Apple is a fruit</li>
    <li data-sort-id="1">Banana is a fruit</li>
</ul>

如何将menuItems对象的新 2、0、1 排序顺序保存到本地存储,以便在检索menuItems时它以新顺序出现?我认为data-sort-id应该以某种方式有所帮助,但不确定如何继续将新订单重新保存到本地存储。知道吗?

更新:

$('.sort-done').click(function(){
    var newSortIds = [];
    $('.sort-menu-items-list').find('li').each(function(){
       newSortIds.push($(this).data('sort-id'));
    });
    console.log(newSortIds); // ["2","0","1"]
});

我需要在上面的代码中添加什么才能使其在 jQuery 中工作?

这是小提琴:http://jsfiddle.net/D2NtS/294/

这样的东西可能会有所帮助

var fruits = [{
  id: "1",
  item: "Apple",
  type: "fruit"
}, {
  id: "2",
  item: "Banana",
  type: "fruit"
}, {
  id: "3",
  item: "Carrot",
  type: "vegetable"
}];
var sortorder = [2, 0, 1]; // get this from localStorage
var i = 0,
  list = document.querySelectorAll("li"),
  len = fruits.length;
for (i; i < len; i++) {
  var ord = sortorder[i];
  list[i].innerHTML = fruits[ord].item + " is a " + fruits[ord].type;
  list[i].setAttribute("data-sort-id", ord);
}
document.getElementById("btn").onclick = function() {
  var ord = [];
  var a = 0;
  for (a; a < len; a++) {
    ord.push(Number(list[a].getAttribute("data-sort-id")))
  }
  alert(JSON.stringify(ord)) // set this to localStorage
}
<ul>
  <li></li>
  <li></li>
  <li></li>
</ul>
<input type="button" id="btn" value="get order">

这段代码会让你得到你要找的东西:

$('.sort-done').click(function(){
    var newSortIds = $.makeArray($('.sort-menu-items-list-sorted-unsaved > li').map(function(i, e) {
        return $(e).data('sort-id');
    }));
    var outputArray = $.makeArray($(menuItems).map(function(i, e) {
        return $(menuItems).filter(function(index, element) { 
           return parseInt(element.id) == parseInt(newSortIds[i]);
        })[0];
    }));
});

需要注意的一点是,outputArray 只是一个对象数组,就像最初的 menuItems 数组一样。我假设你知道你将如何从中填充 ul。如果你不让我知道。

以下是我使用的一些函数的一些链接:

makeArray(): https://api.jquery.com/jQuery.makeArray/

地图(): http://api.jquery.com/jquery.map/

这是您的 JSFiddle 编辑,以使用我上面列出的函数并在页面上显示输出:http://jsfiddle.net/D2NtS/298/

以下策略可以解决您的问题吗?

  1. 从服务器加载菜单项。
  2. 将sort_key属性添加到菜单项的每个项。
  3. 保存菜单本地策略中的项。
  4. 加载菜单从本地策略中的项。
  5. 按sort_key对菜单项进行排序。
  6. 呈现菜单项在 HTML 中。
  7. (前端的用户排序)
  8. 根据用户排序结果重新编号菜单项的每个项sort_key属性。
  9. 保存菜单本地策略中的项。

您需要在重新编号并保存到本地时决定事件。例如,当用户单击排序按钮或用户单击某些保存按钮等时。

代码如下所示。

function loadFromServer(){
    // This is mock code.
    return [
        {
            id: "1",
            item: "Apple",
            type: "fruit"
        },
        {
            id: "2",
            item: "Banana",
            type: "fruit"
        },
        {
            id: "3",
            item: "Carrot",
            type: "vegetable"
        }
    ];
}
function loadFromLocalstrage(){
    // This is mock code.
    return [
        {
            id: "2",
            item: "Banana",
            type: "fruit",
            sort_key: 2
        },
        {
            id: "3",
            item: "Carrot",
            type: "vegetable",
            sort_key: 3
        },
        {
            id: "1",
            item: "Apple",
            type: "fruit",
            sort_key: 1
        }
    ];
}
function addSortKeyAtt(items){
    for (var i = 0, len = items.length; i < len; i++){
        var item = items[i];
        item.sort_key = i;
    }
}
function sortByKey(items){
    return items.sort(function(a, b){
        return a.sort_key - b.sort_key;
    });
}
function userOperation(items){
    // This is mock code.
    var item0 = items[0],
        item1 = items[1],
        item2 = items[2];
    return [
        item2, item0, item1
    ];
}

// #1
var menuItems = loadFromServer();
// #2
addSortKeyAtt(menuItems);
// #3
// Save to localstrage.
// #4
menuItems = loadFromLocalstrage();
// #5
menuItems = sortByKey(menuItems);
// #6
// Render menuItems in HTML.
// #7
menuItems = userOperation(menuItems);
// #8
addSortKeyAtt(menuItems);
// #9
// Save to localstrage.
console.log(menuItems);

更新:

如果你想把它集成到你的jquery代码中,这将帮助你。虽然我写了这个示例,但我建议你尽可能将管理模型数据逻辑与手写 DOM 逻辑分开。

var menuItems = [
    {
        id: "1",
        item: "Apple",
        type: "fruit",
        sort_key: 1
    },
    {
        id: "2",
        item: "Banana",
        type: "fruit",
        sort_key: 2
    },
    {
        id: "3",
        item: "Carrot",
        type: "vegetable",
        sort_key: 3
    }
];
$('.sort-done').click(function(){
    var newMenuItems = [];
    $('.sort-menu-items-list').find('li').each(function(i){
        var id = $(this).data('id');
        // To make code simple, I use underscorejs find function. You could implement the same code if you don't want use underscorejs.
        var item = _.find(menuItems, function(item){
            return item.id === id.toString();
        });
        item.sort_key = i + 1;
        newMenuItems.push(item);
    });
    console.log(newMenuItems);
});

JSFIDDLE在这里。

更新:

如果你不想使用underscorejs,你可以很容易地编写你的find函数。代码将是这样的。

function find(array, iteratee){
    for(var i = 0, len = array.length; i < len; i++){
        var item = array[i];
        if (iteratee(item)){
                return item;
        }
    }
    return undefined;
}

JSFIDDLE在这里。

我希望这对你有所帮助。

最新更新