Help us understand the problem. What is going on with this article?

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

概要

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 オブジェクトに変換される。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした