LoginSignup
7
8

More than 3 years have passed since last update.

【Vue.js】Vue.jsで、forEachを使う時の注意点

Last updated at Posted at 2020-10-11

Vue.jsで使うthis.dataと、forEach文を活用するときは、注意が必要という記事になります。

そもそもforEach文とは


// 配列を繰り返す
offices.forEach(function(office){
  console.log(office)
})

// 繰り返す配列を、thisで取得する
offices.forEach(function(office){
  console.log(this)
}, offices)

第一引数にはコールバック関数を、第二引数には繰り返す配列を定義することで、thisとして取得できる。

結論:forEachのthisと、Vue.jsのthisは別物

forEach文内でのthisは、繰り返す配列のことを指してしまうので、直接格納することができない


// エラーになる
offices.forEach(function(office){
  this.array.push(office)
})

配列の要素を、this.dataの配列に格納したい

以下のような、Vueインスタンスのデータがあるとする。

data () {
  return {
    holidays: [],
  }
}

そして、以下のレスポンスデータを取得して、Vueインスタンスのデータに格納したい。

[
    {
        "id": 1,
        "name": "owada"
        "regular_holidays": [
            {
                "id": 1,
                "holiday": "mon"
            },
            {
                "id": 2,
                "holiday": "tue"
            },
            ・・・省略
        ],
    },
    ・・・省略
]

配列の中のオブジェクトの中の配列の要素を、格納したい時

つまり、"regular_holidays"の要素群をthis.dataに格納する

this.holidays = res.data.regular_holidays.map((day) => day.holiday);

配列の中のオブジェクトの中の配列の中のオブジェクトの値を、格納したい時

つまり、"regular_holidays"の要素のオブジェクトキーである"holiday"this.dataに格納する

const holidays = [];

this.offices.forEach(function (office) {
  office.regular_holidays.forEach(function (day) {
    holidays.push(day.holiday);
  });
});

this.holidays = holidays;

forEach内で、this.dataを取得できないので、うまく工夫する必要がある。

7
8
0

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
7
8