1
1

More than 3 years have passed since last update.

JavaScript (GoogleAppsScript) の入れ子になっている Object をすべて Map に変換する

Last updated at Posted at 2020-02-15

概要

WebAPI などから取得した JSON を JSON.parse() した Object など、値部分にさらに Object が格納されているような場合に、入れ子部分もすべて Map オブジェクトに変換する。
イテラブルなオブジェクトとして処理したい場合に有効。
(GoogleAppsScript では V8 ランタイム使用時のみ可能)

コード

以下のようなクラスを作成した。

class objectToMap {

  constructor(obj) {

    this.object = obj;
    this.map    = this.objToMapProc(obj);

  }

  objToMapProc(obj) {

    let resMap = new Map();

    for (const key in obj) {

      const objValue = obj[key];
      const dataType = typeof objValue;
      let setMapArr  = [];

      if (dataType === 'object') {

        const setMapValue = this.objToMapProc(objValue);
        setMapArr.push(key, setMapValue);

      }else{

        setMapArr.push(key, objValue);

      }

      resMap.set(...setMapArr);

    }

    return resMap;

  }

}

使用方法

function testJsonToMap(){

  const json      = '{"test1": "text1", "test2": {"test2_1": "text2"}, "test3": {"test3_1": {"test3_1_1": "text3"}}}';
  const jsonObj   = JSON.parse(json);
  const jsonToMap = new objectToMap(jsonObj);
  const map       = jsonToMap.map;

  console.log(map.get('test3').get('test3_1').get('test3_1_1')); //'text3'

}

このように、入れ子部分も Map オブジェクトに変換される。

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