简体   繁体   中英

Storing data with help of localstorage

I am storing localstorage data in an array. My code is:

 var a;
//is anything in localstorage?
if (localStorage.getItem('session') === null) {
    a = [];
} else {
     // Parse the serialized data back into an array of objects
     a = JSON.parse(localStorage.getItem('session'));
 }
 // Push the new data (whether it be an object or anything else) onto the array
 a.push(data);
  document.write(a + "<br>")
 // Re-serialize the array back into a string and store it in localStorage
 localStorage.setItem('session', JSON.stringify(a));

where data is:

var data = {name: "abc", place: "xyz"}

On every page refresh, my data is getting multiplied like this:

[{name: "abc", place: "xyz"}, {name: "abc", place: "xyz"}, {name: "abc", place: "xyz"}, {name: "abc", place: "xyz"}]

I want to store data only if value of data changes means instead of {name: "abc", place: "xyz"} , I have {name: "ijk", place: "uvx"} . How can I avoid data getting multiplied on each page refresh?

You have to look into a before inserting new data.

if (!a.some(filterData(data)) {
  a.push(data);
}

function filterData(data) {
  return function(item) {
    return item.name === data.name && item.place === data.place;
  };
}

You could achieve the same thing with a loop:

var found = false;
for (var i = a.length; i--;) {
  if (a[i].name === data.name && a[i].place === data.place) {
    found = true;
    break;
  }
}

if (!found) {
  a.push(data);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM