在数组上使用 Array.reduce 时收到错误

Receiving error when using Array.reduce on array

我试图在具有这种结构的数组上调用此 deepFilter 函数,但我在控制台中收到此错误:TypeError: Cannot read properties of undefined (reading 'reduce'),我不知道为什么。我确定这很简单,但我画的是一片空白。

有人能给我指出正确的方向吗?

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'));

因为你在cur.subitems中的值不是数组。

您可以像这样添加 && cur.subitems 轻松修复它:

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

您正在函数中使用递归,因此您应该相应地检查值。