LoginSignup
1
0

More than 5 years have passed since last update.

連想配列のindexを取得

Last updated at Posted at 2019-02-19

個人的メモ

Reactをやっていて、ある連想配列の中のindexを取得したかった

//classコンポーネントで定義
    this.state = {     
      questions: []
    };
question() {
    const { questions } = this.state;
    // オブジェクト作成
    const q = {
      id: '',
      name: "",
      color: ""
    };
    //ついでに配列に色の文字列を突っ込んで
    const colorArray = ['red','blue','yellow','pink','black','orange','']

    //連想配列のインデックスを取得
    let qindex = Object.keys(questions).length + 1

    //ここでそのオブジェクトにアクセスをしてオブジェクトを更新
    q.id = qindex
    q.color = colorArray[qindex]

    //setStateで更新
    this.setState({
      //配列のマージ
      questions: [...questions, q]
    })
  }

let qindex = Object.keys(questions).length + 1を使って取得

もう少しうまく関数にしてテストできやすくすることが目標

とはいえ、一旦できたのでメモとして記載

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0