4

I have an array of JSON objects like:

 $scope.users = [
    {name:'Maria',age:25,skills["Angular.js","Node.js"]},
    {name:'Maxime',age:28,skills["HTML","MongoDB"]},
    {name:'Noemie',age:28,skills["CSS","MongoDB"]}
 ]

I want to make a search engine. If the user can enter one or multiple words and then my app will filter my variable.

For example, the user enter "28" and "MongoDB", then I put the two queries in an array like

$scope.queries = [28,"MongoDB"]

and filter my array : $scope.users with it.

Please note that $scope.users is not as simple as the example and it has some other arrays which contain arrays etc... So I'll prefer a function to "simply" search for keywords

I would like to know how to do a function or filter.

2
  • I would put this search function in the backend and let SQL handle it. If your dataset get huge, you're gonna have a bad time. Commented May 9, 2016 at 13:29
  • yes, afeter thinking about it, i would do that! Commented May 9, 2016 at 13:36

1 Answer 1

2

Not very optimal, but you can try this

var filterQueries = [28,"MongoDB"];
var filteredResults = $scope.users.filter(function(obj){
  var match = false;
  filterQueries.forEach(function(query){
    if ( obj.name == query || obj.age == query || obj.skills.indexOf( query ) != -1 ) 
    {
       match = true; //assuming you want any of the query to be found rather than all
    }
  });
  return match;
});

DEMO

	 
var users = [
    {name:'Maria',age:25,skills : ["Angular.js","Node.js"]},
    {name:'Maxime',age:28,skills : ["HTML","MongoDB"]},
    {name:'Noemie',age:28,skills : ["CSS","MongoDB"]}
];

var filterQueries = [28,"MongoDB"];
var filteredResults = users.filter(function(obj){
  var match = false;
  filterQueries.forEach(function(query){
    if ( obj.name == query || obj.age == query || obj.skills.indexOf( query ) != -1 ) 
    {
       match = true; //assuming you want any of the query to be found rather than all
    }
  });
  return match;
});

document.body.innerHTML += JSON.stringify( filteredResults, 0, 4 )

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.