Home > Software engineering >  Receiving error when using Array.reduce on array
Receiving error when using Array.reduce on array

Time:05-18

I'm trying to call this deepFilter function on an array with this structure but I am getting this error in the console: TypeError: Cannot read properties of undefined (reading 'reduce') and I can't figure out why. I'm sure it's something simple but I'm drawing a blank.

Can someone point me in the right direction?

const items = [
   {
      "name":"Name1",
      "id":58,
      "sites":[
         {
            "id":106,
            "name": "Name11",
            "items":[
               {
                  "name":"01",
               },
               {              
                  "name":"02",
               },
            ]
         }
      ]
   },
   {
      "name":"Name2",
      "id":47,
      "sites":[
         {
            "name":"Name22",
            "id":106,
            "items":[
               {
                  "name":"03",
               },
               {
                  "name":"04",
               },               
            ]   
         }
      ]
   }
];

const deepFilter = (items, value) => items.reduce((arr, cur) => {
  if (cur.name.includes(value)) arr.push(cur);
  else if (cur.hasOwnProperty('sites')) {
    const subItems = deepFilter(cur.subitems, value);
    if (subItems.length) {
      cur.subitems = subItems;
      arr.push(cur);
    }
  }
  else if (cur.hasOwnProperty('items')) {
    const subSubItems = deepFilter(cur.subsubitems, value);
    if (subSubItems.length) {
      cur.subsubitems = subSubItems;
      arr.push(cur);
    }
  }
  return arr;
}, []);

console.log(deepFilter(items, '02'));

CodePudding user response:

Because your value in cur.subitems is not an array.

you can fix it easily by adding && cur.subitems like this:

else if (cur.hasOwnProperty('sites') && cur.subitems) {

you are using recursion in your function so you should check values accordingly.

  • Related