Question

I just coded a small snippet to play a little bit with localStorage, pretty simple, you can add items to an json array, all these items will be saved under the localStorage key "saved"

However I was not able to prevent double entries in my json array and instead it should fire an alert.

$("#add").on("click", function(e){
    var items = localStorage.getItem('saved');
    var newitem = $('#theitem').val();

    if (items != null){
        var allitems = JSON.parse(localStorage["saved"]);
        allitems.push({"myitem":newitem});
        localStorage.setItem('saved', JSON.stringify(allitems));
    }else{
        var allitems = [{"myitem":newitem}];
        localStorage.setItem('saved', JSON.stringify(allitems));
    }
}); 

Here is the full code: http://jsfiddle.net/Janosch/f0j71/

What part of the '#add' click handler do I need to change in order to prevent duplicates?

Était-ce utile?

La solution

This should work:

    ...
    var allitems = JSON.parse(localStorage["saved"]);
    var repeated=allitems.filter(function(a){ return a.myitem==newitem}).length;
    if(!repeated){
        allitems.push({"myitem":newitem});
        localStorage.setItem('saved', JSON.stringify(allitems));
    }else{alert('already added')}
    ...
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top