根据对象值过滤嵌套的对象数组Javascript ES6

时间:2019-09-19 17:04:49

标签: javascript vue.js ecmascript-6 filter

我正在尝试根据search变量(字符串)过滤对象数组下方。因此,用户可以根据人员的头衔,年份或姓名进行搜索

array = [{
    "title": "Test",
    "year": 2018,
    "people": [
      {
        "name": "person1"
      },
      {
        "name": "person2"
      }],
  },
  {
    "title": "Test2",
    "year": 2018,
    "people": [
      {
        "name": "person3"
      },
      {
        "name": "person4"
      },
      {
        "name": "person5"
      }],
   },...]

我写了下面的函数,该函数对 title year 都适用,但是我不知道如何在其中搜索 people 数组功能。我知道在没有ES6的情况下如何做,但我更喜欢ES6,这仍然让我感到困惑:

filteredArray() {
            let search = this.search.toLowerCase();
            return this.array.filter(function (item) {
                    return Object.values(item).some(val =>
                        String(val).toLowerCase().includes(search));
            })
        },

this.searchv-model,用于保存用户键入的值。 这是Codepen

感谢您的帮助:)

2 个答案:

答案 0 :(得分:1)

以下代码有助于您的用例

   var searchString = 'person5';

   let result = array.filter(ele => 
    ele.title.includes(searchString)
    || `${ele.year}`.includes(searchString)
    || ele.people.some(pele => pele.name.includes(searchString))
   )
   console.log(JSON.stringify(result));

答案 1 :(得分:0)

创建搜索字符串的映射/哈希以轻松搜索:

const array = [{
"title": "Test",
"year": 2018,
"people": [
  {
    "name": "person1"
  },
  {
    "name": "person2"
  }],
  },
  {
"title": "Test2",
"year": 2018,
"people": [
  {
    "name": "person3"
  },
  {
    "name": "person4"
  },
  {
    "name": "person5"
  }],
   }];


let map = array.reduce((map,item,i)=>{
  let values = Object.values(item);
  let persons = values.pop().map(e=>e.name);
  [...values,...persons].forEach(e=>map.set(String(e).toLowerCase(),i))
  return map;
},new Map());

//console.log(...map);
['person1','person3','Test2'].forEach(e=>console.log({[e]:array[map.get(String(e).toLowerCase())]}))
 

对于Vue,请尝试

filteredArray() {
    let search = this.search.toLowerCase();
    let arr2d = this.arr2d;
    if(typeof arr2d ==="undefined"){
     arr2d = this.array.reduce((arr,item)=>{
      let values = Object.values(item);
      let persons = values.pop().map(e=>e.name);
      arr.push([...values,...persons]);
      return arr;
     },[]);
    }
    return this.array.filter((item,i)=>arr2d[i].some(el=>
        String(el).toLowerCase().includes(search)))
    }