首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从对象数组中搜索“标题”&只返回与searchTerm匹配的对象?

如何从对象数组中搜索“标题”&只返回与searchTerm匹配的对象?
EN

Stack Overflow用户
提问于 2017-08-26 10:06:50
回答 1查看 45关注 0票数 1

真是个新手!我在尝试重新植入一个旋转的图像.基于一系列搜索结果。但确实遇到了令人惊讶的问题。

我正在使用JS/Jquery,并且拥有一个从api中存在的对象数组:

代码语言:javascript
复制
let arrayOfObjects = [ 
{id: 0, title: 'Beauty & The Beast', img: 'https://imgthing1.com' }, 
{id: 1, title: 'The Brainiac', img: 'https://imgthing2.com' }, 
{id: 2, title: 'Mac and Me', img: 'https://imgthing3.com' }
];

然后我有了我想要过滤数组的searchTerm,并从以下返回一个新的结果数组:

代码语言:javascript
复制
function checkWords(searchTerm, arr) {
    let results = [];
    let st = searchTerm.toLowerCase();

// **** i map through the array - if the search term (say its 'a' is the same
// as the first character of an object's 'title'... then it stores
// that object in results, ready to be rendered. ****

    arr.map((each) => {
      if (st === each.title.charAt(0)) {
         results.push(each)
      }
    })

    console.log(finalResults);

}

但我想不出如何保持它的匹配..。基于:“比”和“美女与野兽”-传球。“吃”和“美女与野兽”-失败。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-26 10:13:44

您可以使用Array#filter并检查字符串是否包含位于零位置的想要的字符串。

代码语言:javascript
复制
let arrayOfObjects = [{ id: 0, title: 'Beauty & The Beast', img: 'https://imgthing1.com' }, { id: 1, title: 'The Brainiac', img: 'https://imgthing2.com' }, { id: 2, title: 'Mac and Me', img: 'https://imgthing3.com' }];


function checkWords(searchTerm, arr) {
    let st = searchTerm.toLowerCase();
    return arr.filter(each => each.title.toLowerCase().indexOf(st) === 0);
}

console.log(checkWords('bea', arrayOfObjects));

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45894227

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档