1

I have an array that contains an array and inside of that array there are several objects.

I want to filter it based on a category id that is passed to it and if any elements in the array match it would return back the filtered array.

the structure of the data is like this:

var myArr = [{
               id:"1",
               category: [{
                   id:"1",
                   name:"cat 1"
               }, {
                   id:"2",
                   name:"cat 2"
               }];
            },{
               id:"2",
               category: [{
                   id:"2",
                   name:"cat 2"
               }, {
                   id:"3",
                   name:"cat 3"
               }];
           },{
               id:"3",
               category: [{
                   id:"3",
                   name:"cat 3"
               }, {
                   id:"4",
                   name:"cat 4"
               }];
           }];

How can I filter this array to return only the elements that have a category id that is equal to 2 for instance?

Here is my code:

  const p3 = $scope.myArr.filter(arr => {

                   return arr.category.includes("2");
                });
                console.log(p3);

i get this error when trying the above code:

"TypeError: Cannot read properties of undefined (reading 'includes')"
ojsl
  • 97
  • 5

0 Answers0