首页 > 解决方案 > 搜索/过滤嵌套数组 Javascript/Lodash

问题描述

对于我的 React.js 项目,我想创建一个嵌套数组的搜索过滤器。用户将使用输入字段进行搜索。

    var dataExample = [
  {
    type: "human", details: [
    {id: 1, name: "Peter", description: "friendly, black-hair"},
    {id: 5, name: "Susan", description: "blond"}
      ]
  },

  {
    type: "animal", details: [
    {id: 2, name: "Will", description: "lazy, cute"},
    {id: 3, name: "Bonny", description: "beautiful"}
      ]
  }
];

在我的搜索输入字段中,我想在“描述”中查找“名称”或其他内容。数组的数据结构应该保持不变。

我搜索“友好”“彼得”时的输出应该是:

[
  {
    type: "human", details: [
    {id: 1, name: "Peter", description: "friendly, black-hair"}
      ]
  }
];

现在我尝试了这样的事情:

  let myfilter = dataExample.filter((data) => {
  data.details.filter((items) => {
    return (items.type.indexOf("human") !== -1 ||       //input of user
              items.description.indexOf("friendly"))
  })
})

不幸的是,这不是它的工作方式。有谁能够帮我?Lodash 也没有问题。太感谢了。

标签: javascriptarrayssearchfilternested

解决方案


您可以使用array#reducewitharray#filter和 来检查您可以使用的单词string#incldues

const dataExample = [ { type: "human", details: [ {id: 1, name: "Peter", description: "friendly, black-hair"}, {id: 5, name: "Susan", description: "blond"} ] }, { type: "animal",details: [ {id: 2, name: "Will", description: "lazy, cute"}, {id: 3, name: "Bonny", description: "beautiful"} ] } ],
  term = 'Peter',
  result = dataExample.reduce((r, {type,details}) => {
      let o = details.filter(({name,description}) => name.includes(term) || description.includes(term));
      if(o && o.length)
        r.push({type, details : [...o]});
      return r;
  },[]);
console.log(result);


推荐阅读