Check if a cookie array element exists

1.2k Views Asked by At

How can I check that an array element already exists within cookie?

Here is my code:

var cookieList = function (cookieName) {
    var cookie = Cookies.get(cookieName);
    var items = cookie ? cookie.split(/,/) : new Array();

    return {
        "add": function (val) {
            items.push(val);
            Cookies.set(cookieName, items.join(','), { path: '/' });
        }
    }
}

var list = new cookieList("MyItems");

$('.items').on('click', '.add', function () {
    var imageId = $(this).data("id");
    list.add(JSON.stringify(imageId));
});
2

There are 2 best solutions below

0
On BEST ANSWER

You can add a method exists to cookieList and then check whether the passed value exists in the items array using Array.indexOf()

var cookieList = function (cookieName) {
    var cookie = Cookies.get(cookieName);
    var items = cookie ? cookie.split(/,/) : new Array();

    return {
        "add": function (val) {
            items.push(val);
            Cookies.set(cookieName, items.join(','), {
                path: '/'
            });
        },
        exists: function (val) {
            return items.indexOf(val) > -1
        }
    }
}

var list = new cookieList("MyItems");

$('.items').on('click', '.add', function () {
    var imageId = $(this).data("id");
    list.add(JSON.stringify(imageId));
    var exists = list.exists(JSON.stringify(imageId))
});

Demo: Fiddle

0
On

FWIW, js-cookie handles JSON out of the box:

var cookieList = function (cookieName) {
    var items = Cookies.getJSON(cookieName) || [];

    return {
        add: function (val) {
            items.push(val);
            Cookies.set(cookieName, items);
            // "path: /" is default,
            // see https://github.com/js-cookie/js-cookie/tree/v2.0.2#path
        },
        exists: function (val) {
            return items.indexOf(val) > -1
        }
    }
}

var list = new cookieList("MyItems");

$('.items').on('click', '.add', function () {
    var imageId = $(this).data("id");
    list.add(JSON.stringify(imageId));
    var exists = list.exists(JSON.stringify(imageId))
});

see https://github.com/js-cookie/js-cookie/tree/v2.0.2#json