[英]filter nested array of objects based on object values Javascript ES6
I am trying to filter below array of objects against search
variable which is a string.我正在尝试针对作为字符串的search
变量过滤下面的对象数组。 So, user can search based on title, year or name of people因此,用户可以根据标题、年份或人名进行搜索
array = [{
"title": "Test",
"year": 2018,
"people": [
{
"name": "person1"
},
{
"name": "person2"
}],
},
{
"title": "Test2",
"year": 2018,
"people": [
{
"name": "person3"
},
{
"name": "person4"
},
{
"name": "person5"
}],
},...]
I have written the below function which works fine for title and year but I could not figure out how to search the people array inside the function.我写了下面的 function,它适用于标题和年份,但我不知道如何搜索 function 中的人员数组。 I know how to do it without ES6 but I prefer ES6 which is still confusing to me:我知道如何在没有 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.search
is the v-model
that holds the value user types in. Here is the Codepen this.search
是保存用户输入值的v-model
。这是Codepen
I appreciate your help:)我感谢您的帮助:)
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));
Create a Map/hash of search strings to easily search:创建搜索字符串的 Map/hash 以轻松搜索:
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对于 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)))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.