Is there an easier, better or cleaner way to filter a list of elements that utilize a data- attribute holding an array?
Currently we have a large list of items each containing 1 or more tags in an array stored in a "data-tags" attribute, as follows:
<div class="viewItem" data-tags='[{"id":1,"name":"Tag 01"},{"id":2,"name":"Tag 02"}]'></div>
<div class="viewItem" data-tags='[{"id":2,"name":"Tag 02"}]'></div>
<div class="viewItem" data-tags='[{"id":1,"name":"Tag 01"},{"id":3,"name":"Tag 03"}]'></div>
The object is to show only the divs that have a particular tag in the data-tags array. The following code works, but I feel it's very inefficient when dealing with a large number of items and would like to find a better answer, whether it's using jquery filter or grep or something else.
$(function () {
//Instantiate variables
var $viewItems = $('.viewItem');
var filterId = 2;
//Hide all items in object array.
$viewItems.hide();
//Loop thru EACH item and show only those with matching id in array
$viewItems.each(function () {
var thisItem = $(this);
var array = thisItem.data("tags");
$.each(array, function (i, obj) {
if (obj.id == filterId) { thisItem.show(); return false; }
});
});
});