1

I apologise if this has been asked before but I can't seem to find a solution from other posts on here.

I'm trying to build a json array in local storage (which is fine) but want to check if an entry already exists before adding new values.

The Json itself

[{"title":"title1","url":"somefile1.pdf","background":"bg1.png"},
{"title":"title2","url":"somefile2.pdf","background":"bg2.png"},
{"title":"title3","url":"somefile3.pdf","background":"bg3.png"}]

Now how would I query the array to ensure only unique entries are being added?

Heres the code to add to array with

var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];

        var newItem = {
            'title': title,
            'url': url,
            'background': background
        };

        // Need to check the newItem is unique here //

        oldItems.push(newItem);
        localStorage.setItem('itemsArray', JSON.stringify(oldItems));

I thought I could use the jquery unique function instead before setting the localstorage object

var cleanedItems = $.unique(oldItems);
localStorage.setItem('itemsArray', JSON.stringify(cleanedItems));

but that didnt work...

Carl Wilson
  • 189
  • 1
  • 11
  • Don't use an array, use an object whose key is whatever property uniquely identifies the elements. – Barmar Nov 09 '13 at 00:05
  • this might be helpful : http://stackoverflow.com/questions/13486479/javascript-array-unique – pax162 Nov 09 '13 at 00:09
  • Object key comparison is not simple - https://github.com/joyent/node/blob/e4cef1a0833e6d677298600e205a142d15639bf2/lib/assert.js#L205-L247 – kavun Nov 09 '13 at 00:37

1 Answers1

1

You will have to loop over each of the items in the array that is parsed from local storage and perform an object equality test with the new item.

Object equality testing is not as simple as obj1 == obj2.

Here are some references to get you started

The following may end up working for you, by using JSON.stringify to compare the new object as a JSON string with the objects in the old array as JSON strings.

function objInArr(newObj, oldItems) {
    var newObjJSON = JSON.stringify(newObj);
    for (var i = 0, l = oldItems.length; i < l; i++) {
        if (JSON.stringify(oldItems[i]) === newObjJSON) {
            return true;
        }
    }
    return false;
}

var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];

var newItem = {
    'title': title,
    'url': url,
    'background': background
};

// Need to check the newItem is unique here
if (!objInArr(newItem, oldItems)) {
    oldItems.push(newItem);
}
localStorage.setItem('itemsArray', JSON.stringify(oldItems));
kavun
  • 3,358
  • 3
  • 25
  • 45
  • absolutely awesome - works exactly as I need and it's much appreciated.. I've been head scratching for a good few hours on this.. – Carl Wilson Nov 09 '13 at 00:53