Uncaught TypeError: x.map is not a functionの対処法

  • 2021年8月1日
  • 2021年10月7日
  • JavaScript
  • 2200view

エラー内容

Uncaught TypeError: x.map is not a function

該当箇所

sample.map( item => {
 // 処理
})

sampleに対してmapで処理を回して行きたい。

解決策

mapを使う為には、操作対象のオブジェクトがmapメソッドを持っていなくてはいけないらしい。

参考)

https://qiita.com/mk-tool/items/cdf80eeef761e8219711

まずは型の確認をする。

console.log(typeof(sample));

これでarray型が出れば問題ないが、違う場合はarray型に直す必要がある。

objectの場合、object→arrayにするにはObject.values()を使う。

以下のコードならエラーは出ずにmapを実行できる。

Object.values(sample).map(item => {
 // 処理
})

以上。

Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
  • Attributes
  • Custom attributes
  • Custom fields
Click outside to hide the compare bar
Compare
Compare ×
Let's Compare! Continue shopping