TypeScript(ES)でオブジェクトの配列をAND検索で絞り込み
9456 ワード
TypeScriptでオブジェクトの複数格納された配列から文字列検索をする
Itemの型(一例)
class Item {
public id!: number;
public name!: string;
public subtitle!: string;
}
Itemの配列から、nameとsubtitleで検索をしてItemの配列を返す関数
// Item型の配列と検索ワードを受け取りItem型の配列を返す関数
function getSearchedItems(items: Item[], keyword: string): Item[] {
// filterで条件に合う物だけを返す配列に入れていく
const searchedItems = items.filter(item => {
const keywords: string[] = keyword.split(/[ ]/g); //半角スペースと全角スペースで切り分ける
const searched =
(item.name ? item.name : "") + (item.subtitle ? item.subtitle : "");//検索されるワードをくっつける
//検索ワードごとに文字列内に見つかるかを確認し、全てのワードが見つかればtrueを返す(Filter済みの配列に追加される)
return keywords.every(keyword => {
return searched.search(keywords[0]) > -1;
});
});
return searchedItems;
}
class Item {
public id!: number;
public name!: string;
public subtitle!: string;
}
// Item型の配列と検索ワードを受け取りItem型の配列を返す関数
function getSearchedItems(items: Item[], keyword: string): Item[] {
// filterで条件に合う物だけを返す配列に入れていく
const searchedItems = items.filter(item => {
const keywords: string[] = keyword.split(/[ ]/g); //半角スペースと全角スペースで切り分ける
const searched =
(item.name ? item.name : "") + (item.subtitle ? item.subtitle : "");//検索されるワードをくっつける
//検索ワードごとに文字列内に見つかるかを確認し、全てのワードが見つかればtrueを返す(Filter済みの配列に追加される)
return keywords.every(keyword => {
return searched.search(keywords[0]) > -1;
});
});
return searchedItems;
}
実際に検索をしてみる例
class Item {
public id!: number;
public name!: string;
public subtitle!: string;
}
function getSearchedItems(items: Item[], keyword: string): Item[] {
const searchedItems = items.filter(item => {
const keywords: string[] = keyword.split(/[ ]/g); //半角スペースと全角スペースで切り分ける
const searched =
(item.name ? item.name : "") + (item.subtitle ? item.subtitle : "");
return keywords.every(keyword => {
return searched.search(keywords[0]) > -1;
});
});
return searchedItems;
}
// 検索する配列
const items: Item[] = [
{
id: 1,
name: "Kingdom hearts",
subtitle: "大好評発売中"
},
{
id: 2,
name: "Acecombat",
subtitle: "Steam版もうすぐ発売"
},
{
id: 3,
name: "League of Legends",
subtitle: "Season 9 start"
},
];
// 検索して結果を表示
console.log(getSearchedItems(items, "Steam Ace"));
あまり調べずにこうなってしまったのでベストプラクティスがあれば教えてください。
→頂いていたご指摘修正しました。
Author And Source
この問題について(TypeScript(ES)でオブジェクトの配列をAND検索で絞り込み), 我々は、より多くの情報をここで見つけました https://qiita.com/unotovive/items/d015c1a0b9b994ea8343著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .