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

javascript エラー「Uncaught TypeError: xxxxx.has 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 106.0.5249.119

エラー内容

以下の、「オブジェクト」に対して「has」で値の存在確認を実行した際に発生。

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

console.log( obj.has('name') );

エラーメッセージ

Uncaught TypeError: obj.has is not a function

画像

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

Uncaught TypeError: obj.has is not a function

画像

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

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

画像

原因

「has」は「map」オブジェクト以外には使用できないため

解決方法

「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.has('name') ); // true
console.log( m.has('address') ); // false

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

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

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

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

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

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