LoginSignup
2
3

More than 5 years have passed since last update.

jsonで受け取った値を、classのthisにしてしまう

Last updated at Posted at 2018-01-17

Vue.jsの案件で用意したAPI叩いた時に得られた値を、_.forEachを使ってthisとして扱うするclassを用意した。


lodashを使える用意しておく。

npm i lodash --save-dev

jsで読み込んでおく。

import _ from 'lodash';

得られるjson

var jsonSmaple = {
  "id": "0001",
  "type": "donut",
  "name": "Cake",
  "ppu": 0.55,
  "batters":
  {
    "batter":
    [
      { "id": "1001", "type": "Regular" },
      { "id": "1002", "type": "Chocolate" },
      { "id": "1003", "type": "Blueberry" },
      { "id": "1004", "type": "Devil's Food" }
    ]
  },
  "topping":
  [
    { "id": "5001", "type": "None" },
    { "id": "5002", "type": "Glazed" },
    { "id": "5005", "type": "Sugar" },
    { "id": "5007", "type": "Powdered Sugar" },
    { "id": "5006", "type": "Chocolate with Sprinkles" },
    { "id": "5003", "type": "Chocolate" },
    { "id": "5004", "type": "Maple" }
  ]
}

jsonを受け取った時、_.forEachを使ってthisに入れて行く汎用Classを用意する。

class BaseEntity {
    constructor(attributes){
      this.from(attributes)
    }

    from(attributes){
      _.forEach(attributes, (value, key) =>{
        this[key] = value;
      });
    }
}

jsonのkeyをthisにさせるClass

class Pancake extends BaseEntity{
  displayConsole(){

    console.log(this);

    let len = this.topping.length;
    let i = 0
    for(i; i< len; i++){
      console.log(this.topping[i].type);
    }
  }
}

var test = new Pancake(jsonSmaple);
test.displayConsole();

スクリーンショット 2018-01-17 11.55.45.png


・使わせていただいたjson
https://adobe.github.io/Spry/samples/data_region/JSONDataSetSample.html

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