Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  76] [ 3]  / answers: 1 / hits: 16936  / 8 Years ago, mon, october 31, 2016, 12:00:00

I have an array, filter and keyword.
i want to search in that array using filter and keyword, with result array of object too. Just like first array.



var data = [
{email: [email protected],nama:User A, Level:Super Admin},
{email: [email protected],nama:User B, Level:Super Admin},
{email: [email protected],nama:User C, Level:Standart},
{email: [email protected],nama:User D, Level:Standart},
{email: [email protected],nama:User E, Level:Admin},
{email: [email protected],nama:User F, Level:Standart}
];
var filter = Level;
var keyword = Standart;

//--------Search


console.log(data);

More From » jquery

 Answers
26

You can use the Array.prototype.filter function which takes a callback and filters accordingly. Per the documentation:




The filter() method creates a new array with all elements that pass the test implemented by the provided function.




The callback, which is the provided function, takes three arguments. From the documentation:




callback



Function is a predicate, to test each element of the array. Return true to keep the element, false otherwise, taking three arguments:



element



The current element being processed in the array.



index



The index of the current element being processed in the array.



array



The array filter was called upon.




We may use element to check the current element and test if it should be filtered or not, like so:





var data = [
{email: [email protected],nama:User A, Level:Super Admin},
{email: [email protected],nama:User B, Level:Super Admin},
{email: [email protected],nama:User C, Level:Standart},
{email: [email protected],nama:User D, Level:Standart},
{email: [email protected],nama:User E, Level:Admin},
{email: [email protected],nama:User F, Level:Standart}
];
var filter = Level;
var keyword = Standart;

var filteredData = data.filter(function(obj) {
return obj[filter] === keyword;
});

console.log(filteredData);





Here, we use a callback (the test) that checks if the current element (obj)'s property specified in filter is strictly equal to keyword. If it passes, it is kept, and thus all objects with property Level with vale Standart are kept. You can also shorten this with ES6 arrow functions:



var filteredData = data.filter((obj) => obj[filter] === keyword);


This is just shorthand for the above. It is effectively the same, returning true or false based on if the current element's Level property is strictly equal to keyword.


[#60239] Wednesday, October 26, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mickaylag

Total Points: 333
Total Questions: 108
Total Answers: 93

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
;