kpimov
kpimov

Reputation: 13922

Sharing objects between two localStorage items

At the moment I have two localStorage items storing arrays of objects that sum up to this, where arr is an array of objects unrelated to those in the items' arrays:

{
    name: 'foo',
    arr: []
}

Both items can have the same object in their objects' arr, but I don't want to duplicate each one shared between them to help avoid hitting the storage limit. How would I go about doing this?

Upvotes: 2

Views: 60

Answers (1)

Arash Milani
Arash Milani

Reputation: 6308

You can calculate the md5 hash of arr content and store each arr in separate localStorage item and set the hash value as the value of key of that localStorage item. (Note the md5 function is not a native one)

var key = md5(arr.toString());
localStorage.setItem(key, arr.toString());

now the object we will be storing will look like this:

{
  name: 'foo',
  arr: key   //note we are just storing a small key here
}

Now as the objects with the same content will have the same hash value, if happens you need to store an object with the same arr values, you will not use extra storage space.

Upvotes: 1

Related Questions