Léo*_*oco 15 javascript arrays lodash
我想知道什么是最干净的方法,根据a过滤对象数组的更好方法string keyword.必须在对象的任何属性中进行搜索.
当我输入时,lea我想通过所有对象及其所有属性来返回包含的对象lea
当我输入时,italy我想通过所有对象及其所有属性来返回包含的对象italy.
我知道tere有很多解决方案,但到目前为止我只看到了一些你需要指定你想要匹配的属性.
ES6并lodash欢迎!
const arrayOfObject = [{
name: 'Paul',
country: 'Canada',
}, {
name: 'Lea',
country: 'Italy',
}, {
name: 'John',
country: 'Italy',
}, ];
filterByValue(arrayOfObject, 'lea') // => [{name: 'Lea',country: 'Italy'}]
filterByValue(arrayOfObject, 'ita') // => [{name: 'Lea',country: 'Italy'}, {name: 'John',country: 'Italy'}]Run Code Online (Sandbox Code Playgroud)
Nin*_*olz 35
您可以对其进行过滤并仅搜索一次搜索字符串.
使用的方法:
Array#filter,仅用于过滤具有条件的数组,
Object.keys 获取对象的所有属性名称,
Array#some 如果发现,迭代键和退出循环,
String#toLowerCase 为获得可比价值,
String#includes 用于检查两个字符串,如果一个包含另一个.
function filterByValue(array, string) {
return array.filter(o =>
Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));
}
const arrayOfObject = [{ name: 'Paul', country: 'Canada', }, { name: 'Lea', country: 'Italy', }, { name: 'John', country: 'Italy' }];
console.log(filterByValue(arrayOfObject, 'lea')); // [{name: 'Lea', country: 'Italy'}]
console.log(filterByValue(arrayOfObject, 'ita')); // [{name: 'Lea', country: 'Italy'}, {name: 'John', country: 'Italy'}]Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
使用 Object.keys 循环遍历对象的属性。使用 reduce 和 filter 使代码更高效:
const results = arrayOfObject.filter((obj)=>{
return Object.keys(obj).reduce((acc, curr)=>{
return acc || obj[curr].toLowerCase().includes(term);
}, false);
});
Run Code Online (Sandbox Code Playgroud)
其中 term 是您的搜索词。
好吧,当我们已经知道它不会使用方法搜索对象时,可以执行以下操作来节省时间复杂度:
function filterByValue(array, value) {
return array.filter((data) => JSON.stringify(data).toLowerCase().indexOf(value.toLowerCase()) !== -1);
}
Run Code Online (Sandbox Code Playgroud)
您始终可以使用array.filter()然后循环访问每个对象,如果任何值与您正在查找的值匹配,则返回该对象。
const arrayOfObject = [{
name: 'Paul',
country: 'Canada',
}, {
name: 'Lea',
country: 'Italy',
}, {
name: 'John',
country: 'Italy',
}, ];
let lea = arrayOfObject.filter(function(obj){
//loop through each object
for(key in obj){
//check if object value contains value you are looking for
if(obj[key].includes('Lea')){
//add this object to the filtered array
return obj;
}
}
});
console.log(lea);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23495 次 |
| 最近记录: |