javascript エラー「Uncaught TypeError: xxxxx.get is not a function」の解決方法

javascript エラー「Uncaught TypeError: xxxxx.get is not a function」の解決方法

javascriptで、エラー「Uncaught TypeError: xxxxx.get is not a function」が発生した場合の原因と解決方法を記述してます。「map」以外の値に使用した際に発生します。「chrome」や「firefox」や「safari」の各ブラウザのエラーメッセージの画像もキャプチャしてます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 108.0.5359.125

エラー内容

以下の、「オブジェクト」に対して「get」を実行した際に発生。

const obj = {name:'mebee',age:25};

const result = obj.get('name');

エラーメッセージ

Uncaught TypeError: obj.get is not a function

画像

firefox105の場合でも同じエラーが発生します。

Uncaught TypeError: obj.get is not a function

画像

safari15.5では、以下のエラーとなります。

TypeError: obj.get is not a function. (In 'obj.get('name')', 'obj.get' is undefined)

画像

原因

「map」オブジェクト以外に「get」を使用しているため

解決方法

「Object.entries」などで「map」に変換してから実行する

let obj = {name:'mebee',age:25};

const m = new Map(Object.entries(obj));

console.log( m ); // {'name' => 'mebee', 'age' => 25}

console.log( m.get('name') ); // mebee
console.log( m.get('age') ); // 25

// オブジェクトに戻す処理
obj = Object.fromEntries(m);

console.log(obj); // {name: 'mebee', age: 25}

または、「map」であるかを判定してから使用します。

let obj = {name:'mebee',age:25};

const result = obj instanceof Map ? obj.get('name') : 'mapオブジェクトではありません';

console.log( result ); 
// mapオブジェクトではありません