Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    });
});
like image 435
Marco Cano Avatar asked Apr 11 '18 16:04

Marco Cano


1 Answers

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);
like image 57
Eddie Avatar answered Sep 23 '22 21:09

Eddie