前提・実現したいこと
事前に用意した2種類の配列(下記A,B)を組み合わせてオブジェクトを生成。それを要素として持つ配列を生成したい。
[配列A]
["アクション","スポーツ","ファンタジー"]
[配列B]
["タイトル1","タイトル2","タイトル3","タイトル4","タイトル5"]
[オブジェクト(※1)]
{"タイトル1":"アクション"}
{"タイトル2":"ファンタジー"}
{"タイトル3":"アクション"}
{"タイトル4":"スポーツ"}
{"タイトル5":"スポーツ"}
※1:{キー:プロパティ値}の組み合わせはランダムで決める。
[配列(最終形態)]
[{"タイトル1":"アクション"},
{"タイトル2":"ファンタジー"},
{"タイトル3":"アクション"},
{"タイトル4":"スポーツ"},
{"タイトル5":"スポーツ"}]
発生している問題・エラーメッセージ
生成したオブジェクトを対象の配列へ格納する処理のところ(「{titles[index]:...}」)でエラーが発生してしまう。
javascript
1export const getData = () => { 2 const titles = getTitle(); 3 const categories = getCategory(); 4 5 const data = [] 6 titles.forEach((test, index) => ( 7 data.push( 8 { titles[index]: categories[Math.floor(Math.random() * categories.length)] } 9 ) 10 )) 11 return data 12}
[エラー内容]
Parsing error: Unexpected token, expected ","
[補足]
getTitleメソッドでは上記の配列Aを生成。
getCategoryメソッドでは上記の配列Bを生成。
考えられること
配列への追加処理を(基礎的なことも含めて)いくつか検証。
おそらくオブジェクトをpushする実装方法に問題があると推測。
ただし、それを解決する方法が見えていない状況です。
[正常終了するパターン]
data.push(titles[index])
→dataの中身:
["タイトル1","タイトル2","タイトル3","タイトル4","タイトル5"]
data.push({ test: categories[Math.floor(Math.random() * categories.length)] })
→dataの中身:
[{"test":"アクション"},
{"test":"ファンタジー"},
{"test":"アクション"},
{"test":"スポーツ"},
{"test":"スポーツ"}]
[異常終了するパターン]
data.push({ titles[index]: categories[Math.floor(Math.random() * categories.length)] })
→[Parsing error: Unexpected token, expected ","]が発生。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/05/16 00:23