使用JSON导出/导入ECMASCRIPT 6类

时间:2016-01-10 23:45:53

标签: json ecmascript-6

这都是使用ecmascript 6;说我有一个班级

class Hero {
    constructor(id,name){
        this.id=id;
        this.name=name;
    }
}

我想创建一个这类类型的对象数组:

var HEROES = [
  { "id": 11, "name": "Mr. Nice" },
  { "id": 12, "name": "Narco" },
  { "id": 13, "name": "Bombasto" },
  { "id": 14, "name": "Celeritas" },
  { "id": 15, "name": "Magneta" },
  { "id": 16, "name": "RubberMan" },
  { "id": 17, "name": "Dynama" },
  { "id": 18, "name": "Dr IQ" },
  { "id": 19, "name": "Magma" },
  { "id": 20, "name": "Tornado" }
];

除了手动解析数组然后为每个元素执行New Hero()之外,有没有办法做到这一点?能够做HEROES[] = hero.jsonExport()然后var = hero.jsonImport(HEROES[i])之类的事情会很高兴。我一直在环顾四周,但没有使用Typescript,这似乎并不容易。我错过了一些容易的事吗? 谢谢! -Eric

1 个答案:

答案 0 :(得分:0)

想要从特定的数组实例导入似乎很奇怪 - 特别是考虑到订单可能会发生变化。导出基于标准创建new Hero的工厂函数可能会更好:

class Hero {
    constructor(id,name){
        this.id=id;
        this.name=name;
    }
}

const HEROES = [
  { "id": 11, "name": "Mr. Nice" },
  { "id": 12, "name": "Narco" },
  { "id": 13, "name": "Bombasto" },
  { "id": 14, "name": "Celeritas" },
  { "id": 15, "name": "Magneta" },
  { "id": 16, "name": "RubberMan" },
  { "id": 17, "name": "Dynama" },
  { "id": 18, "name": "Dr IQ" },
  { "id": 19, "name": "Magma" },
  { "id": 20, "name": "Tornado" }
];

export default function createHero(index) {
    const hero = HEROES[index];
    return new Hero(hero.id,hero.name);
}

来电者:

import createHero from "./hero";
const hero1 = createHero(1);