[Vuejs]-Filter nested array of objects based on object values Javascript ES6

1👍

Following code helps your usecase

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

0👍

Create a Map/hash of search strings to easily search:

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())]}))

For Vue, try

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)))
    }

Leave a comment