-1

I have an array called active_filters which contains objects. Does anyone know how I would be able to access the category property to use like below?

My goal is the following

// For each active filter, use category for:

   $("#" + category).find("input:checked").each(function() 
   {
       // Do something
   }

// End for

Active Filters Array

{category: "search-filter-type", id: "data-type", value: "ICAR,SCAR", type: "filtered-out-by-car-type"}
{category: "search-filter-company", id: "data-company", value: "BU", type: "filtered-out-by-company"}
{category: "search-filter-location", id: "data-location", value: "AV-123", type: "filtered-out-by-location"}
Michael
  • 403
  • 1
  • 9
  • 28

3 Answers3

0

As you have an array of objects you can use $.each() to iterate on them see a demo below.

var json = [{
  category: "search-filter-type",
  id: "data-type",
  value: "ICAR,SCAR",
  type: "filtered-out-by-car-type"
}, {
  category: "search-filter-company",
  id: "data-company",
  value: "BU",
  type: "filtered-out-by-company"
}, {
  category: "search-filter-location",
  id: "data-location",
  value: "AV-123",
  type: "filtered-out-by-location"
}];

$.each(json, function(index, filters) {
  console.log(filters.category);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
0

actually you can loop over your categories and the search for each category inside and use the $("#" + category)

let categories = [{
  category: "search-filter-type",
  id: "data-type",
  value: "ICAR,SCAR",
  type: "filtered-out-by-car-type"
}, {
  category: "search-filter-company",
  id: "data-company",
  value: "BU",
  type: "filtered-out-by-company"
}, {
  category: "search-filter-location",
  id: "data-location",
  value: "AV-123",
  type: "filtered-out-by-location"
}]


categories.forEach(cat => {
  let category = cat.category;
  console.log(category);
  $("#" + category).find("input:checked").each(function() {
    // Do something
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Prince Hernandez
  • 3,623
  • 1
  • 10
  • 19
0

You can use just js for the active_filters, like this:

active_filters = [
    {category: "search-filter-type", id: "data-type", value: "ICAR,SCAR", type: "filtered-out-by-car-type"},
    {category: "search-filter-company", id: "data-company", value: "BU", type: "filtered-out-by-company"},
    {category: "search-filter-location", id: "data-location", value: "AV-123", type: "filtered-out-by-location"}
];

for (var i in active_filters) {
    if (active_filters.hasOwnProperty(i)) {
        var category = active_filters[i];
        $("#" + category).find("input:checked").each(function() {
            // Do something
        }
    }
}
Vaxes
  • 62
  • 8