javascriptを勉強しています。
以下のような配列があり、filter、findを行って、id=1のものを取り出したいのですがundefinedになってしまいます。
アドバイスをいただけますと幸いです。
// ▼配列 const templates: option[] = [ { name: 'オンライン', id: 1 }, { name: 'オフライン', id: 2 }, ] // filterを使用した場合 const target = templates.filter(template => { template.id === 1 }) console.log(target) // ↑[]と空で出力される // findを使用した場合 const target = templates.find(template => { template.id === 1 }) // ↑undefinedと出力される // foreachを資料 templates.forEach(template => { console.log(template.id) if (template.id === 1) { console.log('該当!') } }) // ↑template.idが1の時、問題なく「該当!」と出力される
foreachの時は問題なくtemplate.id === 1で該当のものが取得できます。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/12/08 04:45