我有一个数组、过滤器和关键字。
我想使用过滤器和关键字在该数组中搜索,以及对象的结果数组。就像第一个数组一样。
var data = [
{email: "[email protected] /cdn-cgi/l/email-protection",nama:"User A", Level:"Super Admin"},
{email: "[email protected] /cdn-cgi/l/email-protection",nama:"User B", Level:"Super Admin"},
{email: "[email protected] /cdn-cgi/l/email-protection",nama:"User C", Level:"Standart"},
{email: "[email protected] /cdn-cgi/l/email-protection",nama:"User D", Level:"Standart"},
{email: "[email protected] /cdn-cgi/l/email-protection",nama:"User E", Level:"Admin"},
{email: "[email protected] /cdn-cgi/l/email-protection",nama:"User F", Level:"Standart"}
];
var filter = "Level";
var keyword = "Standart";
//--------Search
console.log(data);
您可以使用Array.prototype.filter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter函数接受回调并进行相应的过滤。根据文档:
The filter()
方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。
回调是提供的函数,它采用三个参数。从文档中:
callback
函数是一个谓词,用于测试数组的每个元素。返回 true 以保留元素,否则返回 false,采用三个参数:
element
数组中当前正在处理的元素。
index
数组中当前正在处理的元素的索引。
array
调用了数组过滤器。
我们可以使用element
检查当前元素并测试是否应该过滤它,如下所示:
var data = [
{email: "[email protected] /cdn-cgi/l/email-protection",nama:"User A", Level:"Super Admin"},
{email: "[email protected] /cdn-cgi/l/email-protection",nama:"User B", Level:"Super Admin"},
{email: "[email protected] /cdn-cgi/l/email-protection",nama:"User C", Level:"Standart"},
{email: "[email protected] /cdn-cgi/l/email-protection",nama:"User D", Level:"Standart"},
{email: "[email protected] /cdn-cgi/l/email-protection",nama:"User E", Level:"Admin"},
{email: "[email protected] /cdn-cgi/l/email-protection",nama:"User F", Level:"Standart"}
];
var filter = "Level";
var keyword = "Standart";
var filteredData = data.filter(function(obj) {
return obj[filter] === keyword;
});
console.log(filteredData);
在这里,我们使用回调(测试)来检查当前元素(obj
) 中指定的属性filter
严格等于keyword
。如果它通过了,它就会被保留,因此所有具有属性的对象Level
与淡水河谷Standart
被存管。您还可以缩短此时间ES6 箭头函数 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions:
var filteredData = data.filter((obj) => obj[filter] === keyword);
这只是上面的简写。它实际上是相同的,根据当前元素是否存在返回 true 或 falseLevel
属性严格等于keyword
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)