Search code examples
javascriptarrayslodash

How do I search an array of objects for any matches containing a string?


I have an array of records with the following pattern:

apis = [{
  info: {
    title: 'some title"
  }
}]

I need to return all records where the user input is the record's title.

I've tried something like this using Lodash but "title" is always a single letter.

this.searchResults = this.apis.filter(function(item){
    return _.some(item.info.title, function (title) {
        return _.includes(title, query);
    });
});

Solution

  • Using ES6 filter, you can:

    let apis = [
      {info: {title: 'select some title'}},
      {info: {title: 'some title 2'}},
      {info: {title: 'some title 3'}}
    ];
    
    let toSearch = 'select'; //Will check if title have text 'search'
    
    let result = apis.filter(o => o.info.title.includes(toSearch));
    
    console.log(result);

    If you want to filter the exact match, you can:

    let apis = [
      {info: {title: 'select some title'}},
      {info: {title: 'some title 2'}},
      {info: {title: 'some title 3'}}
    ];
    
    let toSearch = 'select some title'; 
    
    let result = apis.filter(o=> o.info.title === toSearch);
    
    console.log(result);