こんにちは。KOUKIです。
プログラムを書いていて、JavaScriptの構造体から特定のデータを取得したいという状況に頻繁に出くわします。
本記事では、findIndexを使ったデータの取得方法について、まとめています。
<目次>
データ構造体
データ構造体とは、以下の構造体をさします。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const todos = [ { id: 1, title: "One" }, { id: 2, title: "Two" }, { id: 3, title: "Three" }, { id: 4, title: "Four" }, { id: 5, title: "Five" }, { id: 6, title: "Six" } ]; // index番号が0から取得できる console.log(todos[0]); // -> {id: 1, title: "One"} console.log(todos[5]); // -> {id: 6, title: "Six"} |
本記事でやりたいことは、このデータの中から特定のデータを抜き出したいといった感じのことです。
findIndexとは
findIndexメソッドは、配列内の指定されたテスト関数を満たす最初の要素の位置を返します。
早速使ってみましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
const todos = [ { id: 1, title: "One" }, { id: 2, title: "Two" }, { id: 3, title: "Three" }, { id: 4, title: "Four" }, { id: 5, title: "Five" }, { id: 6, title: "Six" } ]; // indexを取得する関数を定義 function getIndex(wantTodo) { let index = todos.findIndex(todo => { return todo.id === wantTodo.id; }); return index; } // 探したいオブジェクトを定義 const wantTodo = { id: 2, title: "Two" }; console.log(getIndex(wantTodo)); // => index番号が 1 と返却される |
findIndexはコールバック関数を引数に持ちます。
上記の例では、idが2のオブジェクトを検索するための処理を書きました。
これで、検索したいオブジェクトのインデックス番号が取得できるので、あとはそのデータを変更すればOKです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
const todos = [ { id: 1, title: "One" }, { id: 2, title: "Two" }, { id: 3, title: "Three" }, { id: 4, title: "Four" }, { id: 5, title: "Five" }, { id: 6, title: "Six" } ]; // indexを取得する関数を定義 function updateObject(wantTodo) { let index = todos.findIndex(todo => { return todo.id === wantTodo.id; }); todos[index] = wantTodo; return index; } const wantTodo = { id: 2, title: "Update Todo" // 例えばここを変更する }; const index = updateObject(wantTodo); console.log(todos[index]); // -> {id: 2, title: "Update Todo"} |
おわりに
findIndexメソッドは、なかなか便利だと感じていただけたと思います。
しかし、オブジェクトの検索方法はこれ以外にもあると思いますので、「これは!」というものがあれば記事にしたいと思います^^
それでは、また!
最近のコメント