Home > Software engineering >  Exclude the list of objects listed on the variable from the filter
Exclude the list of objects listed on the variable from the filter

Time:07-04

I am working with JSON data and I filter some of the data out using .filter, I want it to exclude some categories and some products, which I can easily do by individually specifying on my filter return, but I reckon the list goes long and it doesn't look feasible the way it is.

I think I don't have to add the example JSON here, just imagine it has "category" and "product" for each data. Have a look how I process the data:

var myfilter = myjson.filter(function(c) {
    return (c.category != 3 && c.category!= 5 && c.category!= 8 && c.category!= 11 && c.product != 191 && c.product != 139 && c.product != "string instead of int");
  });

^This above already does what I need. What I desire is to turn it into something like this:

var excludedcats = [3, 5, 8, 11]
var excludedproducts = [191, 139, "string instead of int"]

var myfilter = myjson.filter(function(c) {
    return (c.category != excludedcats && c.product != excludedproducts);
  });

I am not a javascript pro, but I feel like this works like 'if' conditions and it has to keep repeating c.category != and c.product != for each, so I thought about some sort of loop until it specifies all of them. But I might be totally lost, too.

I already did some research, but could be that since I don't even know all the technical terms either I failed to find what I'm looking for. Most relevant thing I could find was this, it didn't help me, just adding here to prove I researched

  • Related