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();
・使わせていただいたjson
https://adobe.github.io/Spry/samples/data_region/JSONDataSetSample.html