typescript 如何在JSON对象数组中搜索元素

np8igboo  于 2022-12-19  发布在  TypeScript
关注(0)|答案(1)|浏览(270)

我正在尝试为 accordion 数据创建一个搜索过滤器,它必须搜索标题以及里面的内容。它必须搜索name键。
我已经实现了一个相同的函数,但是使用这种方法,我无法在children键中搜索name

let filteredTiles = this.tileData.filter((value) => {  //tileData is the JSON array
    return value.name.toLowerCase().indexOf(searchValue) != -1 ? value : null;
});

如何在JSON数据的子对象中进行搜索?
Demo at Stackblitz
我的JSON数据是

[
    {
      "name": "First",
      "image": "https://img.freepik.com/free-vector/football-2022-tournament-cup-background_206725-604.jpg?size=626&ext=jpg",
      "children": [
        {
          "name": "Firstone",
          "image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
          "url": "http://www.google.com"
        },
        {
          "name": "Firsttwo",
          "image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
          "url": "http://www.google.com"
        },
        {
          "name": "Firstthree",
          "image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
          "url": "http://www.google.com"
        }
      ]
    },
    {
      "name": "Second",
      "image": "https://media.istockphoto.com/id/517188688/photo/mountain-landscape.jpg?s=612x612&w=0&k=20&c=A63koPKaCyIwQWOTFBRWXj_PwCrR4cEoOw2S9Q7yVl8=",
      "children": [
        {
          "name": "Secondone",
          "image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
          "url": "http://www.google.com"
        },
        {
          "name": "Secondtwo",
          "image": "https://media.istockphoto.com/id/517188688/photo/mountain-landscape.jpg?s=612x612&w=0&k=20&c=A63koPKaCyIwQWOTFBRWXj_PwCrR4cEoOw2S9Q7yVl8=",
          "url": "http://www.google.com"
        },
        {
          "name": "Secondthree",
          "image": "https://img.freepik.com/free-vector/hand-painted-watercolor-abstract-watercolor-background_23-2149005675.jpg?size=626&ext=jpg",
          "url": "http://www.google.com"
        }
      ]
    },

]
hrysbysz

hrysbysz1#

这与过滤数组中的对象的方式类似。
在 predicate 中,必须筛选数组中的嵌套对象。如果筛选嵌套数组返回的索引大于-1,则意味着存在满足筛选条件的嵌套对象。
此外,您可以使用Array.some(predicate),它返回布尔值作为Array.findIndex(predicate) > -1的替代。

this.tileData.filter((value) => {
  return 
    value.children.some(
      (c) => c.name.toLowerCase().indexOf(searchValue) > -1
    )
  ;
});

如果要筛选根对象或嵌套子对象是否满足筛选条件,应使用||(或)运算符。

let filteredTiles = this.tileData.filter((value) => {
  return (
    value.name.toLowerCase().indexOf(searchValue) > -1 ||
    value.children.some(
      (c) => c.name.toLowerCase().indexOf(searchValue) > -1
    )
  );
});

Demo @ StackBlitz

相关问题