0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

TypeError:Cannot read properties of undefinedと出た時の対処法

Last updated at Posted at 2023-05-08

本記事は、GASでRESTAPIからJSONデータを得た際に、そのデータの一部を抜き取って表示する処理で発生したエラーを解消した経験を共有することを目的としています。そのため、どうようのエラーが出た際に、本記事の対処方法が適切でない場合がありますので、予めご了承下さい。

それでは行きます!

serch.gas
const companyCode = json.values[0].item_data[0].num;
const result = `企業名001株式会社:担当社員:${companyCode}`;
console.log(result); 

というコードを書き出力しようとしました。
ちなみにこの際変数jsonに代入されていたのは下記データです。

"obj_name" : "customer",
 "item_data" : [ { "column" : { "code" : 318, "name" : "COMPANY_CODE", "type" : 3 }, "column_code" : null, "text" : null, "num" : 10186, "decimal" : null, "date" : null, "checkbox" : null, "values" : null } ] } ] }

そして、上記コードを出力すると
TypeError:Cannot read properties of undefined
の文字が、、
なんでだ!( ; ; )

ただ、よく考えてみると、.values[0].item_data[0].numという書き方はGASのプロパティーでは使えるが、json形式のデータでは使えないのでは、、

そう思い、下記のようにコードを書き換えてみました。

serch.gas
const gasProperty = JSON.parce(json);
const companyCode = gasProperty.values[0].item_data[0].num;
const result = `企業名001株式会社:担当社員:${companyCode}`;
console.log(result); 

すると、企業名001株式会社:担当社員:10186と出力されました!
やはり、json形式をGAS形式に変えなかったことが良くなかったようです!

最後に
有識者の方へ本記事に誤りがあった際には修正しますので、修正依頼を送っていただけますと幸いです。
宜しくお願い致します。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?