0

i want to push an object to an array(last called objects) and store this array to localstorge. this array fills every call with new objects. If an objects still exist in the array, the older one will be replaced.

My code so far:

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

i use this jquery plugin jstorage

im not an js pro and at the moment, only one object get stored correct. So my questions:

  1. How to store an array of objects to local storage, get it back, and add new objects to this array
  2. How to manage that there is only one unique object in this array
  3. How to limit the array by eg the 50 newest and kick the older ones

thx for any suggestions or snippets

EDIT: some people mark this as duplicate - but the linked answer is only a part of my. I read this before but my problem is to set/get an array with unique objects. i think it is more complex.

ses3ion
  • 115
  • 1
  • 5

1 Answers1

1

in your case objects = [] will fail to store it to localStorage change it to objects = {}.

test it

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

for point 1 and 2, since it using object key name there will be no duplicate, it will be overwritten with new value, no other action needed.

for point 3, if you do objects[objKey] = object; it will append object to last position so oldest position to delete is index 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);
}
ewwink
  • 18,382
  • 2
  • 44
  • 54