JasonDavis JasonDavis - 25 days ago 7
jQuery Question

Find matching JSON items between 2 JSON arrays in JavaScript and apply CSS to matching items in a UL list

Using JavaScript I need to take a JSON array of Tag items and generate an HTML UL list of all tags from that JSON data.

Next I have a 2nd JSON data-set of Tags in which I need to look in the first Tag JSON data and find each matching item between the 2 sets of tags.

When a Tag in the 2ns JSON data-set exist in the 1st Tag JSON data-set I need to add a CSS class to the UL list I generated from the 1st Tag data on each matching Tag

1st JSON Tag Data-set

var allTagsJson = [{
"id": "1",
"name": "Tag 1"
}, {
"id": "2",
"name": "Tag 2"
}, {
"id": "3",
"name": "Tag 3"
}, {
"id": "4",
"name": "Tag 4"
}, {
"id": "5",
"name": "Tag 5"
}];


2nd JSON Tag Data-set

"id": "1",
"name": "Tag 1"
}, {
"id": "4",
"name": "Tag 4"
}, {
"id": "5",
"name": "Tag 5"
}];


So in this sample data my UL list would have :


  • Tag 1

  • Tag 2

  • Tag 3

  • Tag 4

  • Tag 5



As the 2nd JSON data-set has tags 1, 4, and 5. The list above would need to add the CSS class
active
to tags 1, 4, and 5

JSFiddle to play with: https://jsfiddle.net/jasondavis/tm9fsyvb/

var listTagsJson = [{

// generate 2 UL lists from JSON Data
$(function() {
var allTagsHtml = '';

// this list needs to add CSS class active to each item that has a matching tag in the 2nd list of tags
$.each(allTagsJson, function(index, val) {
console.log(val.name);
allTagsHtml += " <li><a href='#" + val.name + "'>" + val.name + "</a></li>";
$('#all-tags').html(allTagsHtml);
});

var listTagsHtml = '';
$.each(listTagsJson, function(index, val) {
console.log(val.name);
listTagsHtml += " <li><a href='#" + val.name + "'>" + val.name + "</a></li>";
$('#list-tags').html(listTagsHtml);
});

});

Answer

Assuming the ID's are only property that need comparing .... start with second array and while iterating it store each id as key in a hashmap object then check if it exists while iterating the first array and add class accordingly

$(function() {
  // id object
  var listIds = {}

  var listTagsHtml = '';
  $.each(listTagsJson, function(index, val) {
    // add id to object
    listIds[val.id] = true;
    listTagsHtml += " <li><a href='#" + val.name + "'>" + val.name + "</a></li>";
  });

  var allTagsHtml = '';
  $.each(allTagsJson, function(index, val) { 
    // apply class based on id object
    var className = listIds[val.id] ? 'match' : '';
    allTagsHtml += " <li class='" + className + "'><a href='#" + val.name + "'>" + val.name + "</a></li>";
  });

  // note these don't belong inside the loops when using html string concatenation
  $('#all-tags').html(allTagsHtml);
  $('#list-tags').html(listTagsHtml);

});

This approach requires no additional dom searching or array filtering and is very efficient

DEMO