面临过滤数组对象内对象的问题

问题描述 投票:0回答:1

我在物体下方。

{
categories: [
  {
    "category": {
      "categoryName": "categoryName1"
    },
    "newsletter": [
      {
        "name": "AAA",
        "description": "111"
      },
      {
        "name": "BBB",
        "description": "222"
      },
      {
        "name": "CCC",
        "description": "333"
      },
    ]
  },
  {
    "category": {
      "categoryName": "categoryName2"
    },
    "newsletter": [
      {
        "name": "DDD",
        "description": "444"
      },
      {
        "name": "EEE",
        "description": "555"
      }
    ]
  }
]
}

我正在尝试在类别、名称和描述之间执行搜索操作。

我的逻辑如下。

this.selectedCategoryData = this.categorisedData.filter((item) => {
    const categoryMatch = item.category.categoryName.toLowerCase().includes(filterValueLowercase);
    const newslettersMatch = item.newsletters.some(newsletter =>
        return newsletter.name.toLowerCase().includes(filterValueLowercase) ||
    newsletter.description.toLowerCase().includes(filterValueLowercase);
    );
    return categoryMatch || newslettersMatch;
});

这是我现在的逻辑。但它适用于某些,而不是 OR。目前,它在发现任何内容时返回整个子数组。如果在子数组中找到该值,则返回整个数组。 如何使用 subArray 进行过滤并分配值?

预期输出如下:

第一个场景

filterValue = "AAA" //returns the below object
categories: [
  {
    "category": {
      "categoryName": "categoryName1"
    }
    "newsletter": [
      {
        "name": "AAA",
        "description": "111"
      }
    ]
  }
];

第二种情况:

filterValue = "categoryName1" //returns the below object
categories: [
  {
    "category": {
      "categoryName": "categoryName1"
    }
    "newsletter": [
      {
        "name": "AAA",
        "description": "111"
      },
      {
        "name": "BBB",
        "description": "222"
      },
      {
        "name": "CCC",
        "description": "333"
      },
    ]
  }
];
javascript arrays object search
1个回答
-1
投票
  1. 使用
    Array::reduce()
    组成结果数组
  2. 使用不区分大小写
    RegExp
    来搜索字符串

const result = items.reduce((regex => (r, item) => {

  if(regex.test(item.category.categoryName)){ // category match - reuse the item
    r.push(item);
  }else{ // check news letters
    const newsletter = item.newsletter.filter(e => regex.test(e.name) || regex.test(e.description));
    if(newsletter.length){
      r.push({...item, newsletter});
    }
  }
  return r;
})(new RegExp('aaa', 'i')), []);

console.log(result);
<script>
const items = [
  {
    "category": {
      "categoryName": "categoryName1"
    },
    "newsletter": [
      {
        "name": "AAA",
        "description": "111"
      },
      {
        "name": "BBB",
        "description": "222"
      },
      {
        "name": "CCC",
        "description": "333"
      },
    ]
  },
  {
    "category": {
      "categoryName": "categoryName2"
    },
    "newsletter": [
      {
        "name": "DDD",
        "description": "444"
      },
      {
        "name": "EEE",
        "description": "555"
      }
    ]
  }
];
</script>

© www.soinside.com 2019 - 2024. All rights reserved.