[英]Search and filter through array javascript
請原諒我不知道如何描述我在做什么
我有一個textarea,人們可以寫評論,但他們也可以提到人們使用我已經制作的@mention系統...現在我唯一的問題是,一旦用戶開始輸入@它沒有縮小用戶,所以說我有一個這樣的對象數組..
users = [
{
name: steve,
id: 47
},
{
name: james,
id: 41
},
{
name: guy,
id: 44
},
{
name: troy,
id: 32
}
]
如何根據@
符號后寫的字符串過濾掉數組中的用戶,這樣如果我在文本區域寫@tr,我的users數組現在看起來應該是這樣的
users = [
{
name: troy,
id: 32
}
]
任何幫助,將不勝感激!
使用filter
檢查正在迭代的用戶的name
是否includes
有問題的子字符串:
const users = [ { name: 'steve', id: 47 }, { name: 'james', id: 41 }, { name: 'guy', id: 44 }, { name: 'troy', id: 32 } ]; const substr = 'tr'; console.log( users.filter(({ name }) => name.includes(substr)) );
還要確保您的name
值是字符串 。
我建議使用類似於其他答案的方法,但我會使用startsWith而不是includes,並確保在比較它們時將兩個字符串小寫。 這將為您提供更准確的結果。
const names = [{ name: 'Bob'}, { name: 'Sally' }, { name: 'Frank' }, { name: 'Lester' }, { name: 'Bo' }, { name: 'Salazar' }, { name: 'Frida' }]; const textArea = document.querySelector('[data-id="textarea"]'); const nameWrap = document.querySelector('[data-id="names"]'); function inputListener() { let shouldListen = false; let index; return (e) => { const { value } = e.currentTarget; const currentValue = value[value.length - 1]; if(shouldListen) { if(currentValue === ' ' || value.length - 1 < index) { shouldListen = false; return; } const str = (value.substr(index).match(/@(.+$)/)[1]).toLowerCase(); const html = names .filter(({ name }) => name.toLowerCase().startsWith(str)) .map(({ name }) => `<p>${name}</p>`) .join(''); console.log(html) nameWrap.innerHTML = html; } if(currentValue === '@' && !shouldListen) { shouldListen = true; index = value.length - 1; } } } textArea.addEventListener('input', inputListener())
<textarea data-id="textarea"></textarea> <div data-id="names"></div>
嘗試這個。
let str = "@tr"; var users = [ { name: "steve", id: 47 }, { name: "james", id: 41 }, { name: "guy", id: 44 }, { name: "troy", id: 32 } ]; const filteredUser = users.filter(user => user.name.includes(str.replace(/@/, ""))); console.log(filteredUser);
您可能需要filter
const users = [ { name: 'steve', id: 47 }, { name: 'james', id: 41 }, { name: 'guy', id: 44 }, { name: 'troy', id: 32 }, { name: 'stephon', id: 141 } ]; const partialUserName = 'st'; const output = users.filter(user => user.name.startsWith(partialUserName)); // you can change to contains if that's what you want console.log(output)
您可以嘗試搜索方法
const substr = 'tr';
array.filter(( name ) => {
return (
name.toLowerCase()
.search(substr.toLowerCase()) !== -1
)
希望這有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.