Filtering between two arrays of objects based on value

Viewed 57

I'm trying to filter between two arrays of objects:

   group: [
    { key: "Global ID", value: "gid" },
    { key: "Super ID", value: "sid" },
    { key: "Duper ID", value: "did" },
    { key: "Application", value: "app" },
    { key: "Category", value: "cat" },
    { key: "Subcategory", value: "sub" },
    { key: "Name", value: "name" },
  ],
  whereClause: [
    { k: "gid", op: "=", v: "111" },
    { k: "sid", op: "=", v: "1" },
    { k: "did", op: "=", v: "2" },
    { k: "app", op: "IN", v: ["asd", "dfg"] },
    { k: "cat", op: "=", v: "hjk" },
    { k: "sub", op: "=", v: "errors" },
    { k: "name", op: "=", v: "mo" },
  ],

Basically the idea is - The user selects multiple values from the "group" array, they are stored in "selectedGroup" array, and on a button click there should be a filter that gets the objects from the "whereClause" array that match the contents of the "selected" array - value == k. I've tried filtering them like this:

where: this.whereClause.filter(
          (clause) => clause.k == this.selectedGroup
        ),

But everytime the user selects more than one, it empties the contents of the filtered value...

2 Answers

It is either where there is only one item:

== this.selectedGroup

Or selectedGroup is an array and therefore we need to search for the items in it:

(clause) => this.selectedGroup.some((selectedItem) => 
selectedItem ==clause.k)

Try this.

var group= [
    { key: "Global ID", value: "gid" },
    { key: "Super ID", value: "sid" },
    { key: "Duper ID", value: "did" },
    { key: "Application", value: "app" },
    { key: "Category", value: "cat" },
    { key: "Subcategory", value: "sub" },
    { key: "Name", value: "name" },
 ];
var whereClause= [
    { k: "gid", op: "=", v: "42501" },
    { k: "sid", op: "=", v: "1" },
    { k: "did", op: "=", v: "2" },
    { k: "app", op: "IN", v: ["hss", "smsc"] },
    { k: "cat", op: "=", v: "lte" },
    { k: "sub", op: "=", v: "errors" },
    { k: "name", op: "=", v: "mo" },
 ];
var selectedGroup = [
    { key: "Duper ID", value: "did" },
    { key: "Application", value: "app" },
];

var output = this.whereClause.filter((clause) => this.selectedGroup.some((selected) =>
      selected.value === clause.k));
      
console.log(output);     

Related