2017-08-26 37 views
1

位新手!我正试图根据搜索结果数组重新填充图像旋转木马。但真正遇到令人惊讶的数量的问题。如何从对象数组中搜索“标题”并仅返回与searchTerm匹配的对象?

我使用JS/jQuery和拥有,也就是说,对象的数组,从我的API存在:

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

} 

但我不能工作,如何保持它匹配...依据: “衣” VS“美容&野兽” - 通过。 'Beat'vs'Beauty &野兽' - 失败。

+1

而不是'map'使用'filter'。 – Xufox

+0

'charAt'只会看......一个字符。 – trincot

+0

您需要使用'each.title.indexOf(st)> -1' –

回答

4

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

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

相关问题