localStorage的唯一对象数组

时间:2017-07-24 13:38:22

标签: javascript jquery local-storage

我想将对象推送到数组(最后调用的对象)并将此数组存储到localstorge。此数组使用新对象填充每个调用。如果数组中仍存在对象,则将替换旧对象。

到目前为止我的代码:

function pushToStorage(groupId, objectId, groupIcon, displayString) {

  var objKey = "object_" + groupId + "_" + objectId;

  var objects = storage.get("objects");

  if (objects) {
    console.log($objects);
  } else {
    objects = [];
  }

  var object = {
    groupid: groupId,
    objectid: objectId,
    groupicon: groupIcon,
    display: displayString
  };

  objects[objKey] = object;

  console.log(objects);

  storage.set("objects", objects);
}

我使用这个jquery插件jstorage

我不是js专业版,目前只有一个对象存储正确。 所以我的问题:

  1. 如何将对象数组存储到本地存储,将其取回,并将新对象添加到此数组
  2. 如何管理此数组中只有一个唯一对象
  3. 如何限制数组,例如最新的50和踢旧的
  4. thx任何建议或片段

    编辑:有些人将此标记为重复 - 但链接的答案只是我的一部分。我以前读过这个,但我的问题是设置/获取一个包含唯一对象的数组。我觉得它更复杂。

1 个答案:

答案 0 :(得分:1)

在您的情况下objects = []将无法将其存储到localStorage,将其更改为objects = {}

测试它

var objects = [];
objects['objkey'] = {red:'#FF0000'}
var json_str = JSON.stringify(test);
console.log(json_str)
// []

对于第1点和第2点,因为它使用对象键名称没有重复,它将被新值覆盖,不需要其他操作。

对于第3点,如果你执行objects[objKey] = object;,它会将对象追加到最后一个位置,因此最旧的删除位置是索引0

function pushToStorage(groupId, objectId, groupIcon, displayString) {

  var objKey = "object_" + groupId + "_" + objectId;
  var objects = storage.get("objects");

  if(objects !== null) {
    console.log(objects);
    // if not objKey and length objects more than 50 delete oldest
    if(storage.isSet(objects[objKey]) === false && Object.keys(objects).length == 50){
      // delete oldest object
      delete objects[0];
    }
  }
  else {
    objects = {};
  }

  var object = {
    groupid: groupId,
    objectid: objectId,
    groupicon: groupIcon,
    display: displayString
  };

  objects[objKey] = object;

  //console.log(objects);

  storage.set("objects", objects);
}
相关问题