LoginSignup
2
2

More than 5 years have passed since last update.

複雑な型宣言とデータの扱い

Last updated at Posted at 2016-10-11

クラスのメンバーにオブジェクトを持つ場合、必要以上にクラス宣言をするのも面倒なため、any型などを指定しがちですが、型指定を行うこともできます。
本投稿では、型の宣言方法および、データのset/get方法を記載します。

扱うJSONデータ

[ほにゃらら]部分はキー値ですが、スクリプト側から指定する値です。

{
    "families":{
        [yamada] :{
            "members" :{
                [ichiro] :{
                    "type" : "owner"
                },
                [jiro] :{
                    "type" : "son"
                },
                [kotaro] :{
                    "type" : "dog"
                }
            }

        },
        [satou] :{
            ~省略。構成は同じ~
        }
    }
}

型の定義

ややこしいので、最小単位(ichiroなど)の型定義から順番に行います。

// name = ichiroで、 type = ownerを持つプロパティ
member  : {[name :string] :{type :string}}

// memberの配列
members :[{[name :string] :{type :string}}]

// surname(姓)の下に、membersを持つ
family  :{[surname :string] :[{[name :string] :{type :string}}]}

// familiyの配列
families :[{[surname :string] :[{[name :string] :{type :string}}]}]

プログラムからJSONへ

JSONライクに記載できます。注:es5以上?

  setter(){
    this.member = {["ichiro"]:{type:"owner"}};
    this.members = [{["ichiro"]:{type:"owner"}},{["jiro"]:{type:"son"}}];
    this.family  = {["yamada"] :[{["ichiro"]:{type:"owner"}},{["jiro"]:{type:"son"}}]};
    this.families = [{["yamada"] :[{["ichiro"]:{type:"owner"}},{["jiro"]:{type:"son"}}]},~~省略~~];
  }

値の表示

各値の取得例を記載します。

output(){

  // 1. memberの処理
  // member  : {[name :string] :{type :string}}
    console.log(this.member);
    // {ichiro: {type: "owner"}}

    console.log(Object.keys(this.member)[0]);
    // ichiro

    Object.keys(this.member).forEach(
      (val, idx, ary) => {
        console.log(val);
        // ichiro
        console.log(this.member[val].type);
        // owner
      }
    )

  // 2. membersの処理
  // members :[{[name :string] :{type :string}}]

    console.log(this.members);
    // [{ichiro: {type: "owner"}}, {jiro: {type: "son"}}]

    this.members.forEach(
      val =>  console.log(val)
      // {ichiro: {type: "owner"}}
      // -> あとはmemberの処理方法で処理する
    );

  // 3.familyの処理
  // family  :{[surname :string] :[{[name :string] :{type :string}}]}

    console.log(this.family);
    // yamada: Array (2)
    // 0 {ichiro: {type: "owner"}}
    // 1 {jiro: {type: "son"}}

    console.log(Object.keys(this.family)[0]);
    // yamada

    Object.keys(this.family).forEach(
      val => console.log(this.family[val])
      // [{ichiro: {type: "owner"}}, {jiro: {type: "son"}}]
      // -> あとはmembersの処理方法で処理する
    );


  // 4. familiesの処理は省略
  // families :[{[surname :string] :[{[name :string] :{type :string}}]}]

}

以上です。

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