如何在包含字符串的任何匹配项中搜索对象数组?

时间:2018-04-11 16:46:55

标签: javascript arrays lodash

我有一系列具有以下模式的记录:

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

我需要返回用户输入为记录标题的所有记录。

我尝试使用Lodash这样的东西,但"title"总是一个字母。

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

1 个答案:

答案 0 :(得分:6)

使用ES6 filter,您可以:

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);

如果您想过滤完全匹配,您可以:

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);