javascript - 无法将 json 数据映射到 js 模型

标签 javascript json typescript

我正在尝试将 2 个相似的传入 json 映射到一个 JS 模型,第一个传入的 json 被正确映射,第二个 json 失败。

这是代码

let allInstruments: Instrument[] = [];
      try {
        if (equityInstruments.constructor === Array) {
          equityInstruments.forEach(element => {

            let instrument: Instrument = element;           
            allInstruments.push(instrument);
          });
        } 
        console.log(allInstruments.length + ' after equity processing');
        if (mutualInstruments.constructor === Array) {
          mutualInstruments.forEach(
            element => {

            let instrument = new Instrument(element.wdId.S, element.amcCode.S, element.schemeName.S);
            allInstruments.push(instrument);
          });
        } 
        console.log(allInstruments.length + ' after mutual processing');
      } catch (err) {
        console.log(err);
      }

上面的代码处理了 2 个传入的 json,下面是需要映射的模型,但我得到错误提示

Cannot set property 'S' of undefined

仪器型号:

export class Instrument {

    wdId: { S: string };
    description: { S: string };
    symbol: { S: string };

    public constructor(wdId: string, symbol: string, description: string) {
        this.wdId.S = wdId; //Cannot refer to this.wdId - Error is thrown here, when mutualInstrument is getting mapped
        this.symbol.S = symbol;
        this.description.S = description;
    }

}

最佳答案

export class Instrument {

      wdId = { S: 'null' };
      description = { S: 'null' };
      symbol = { S: 'null' };

      public constructor(wdId: string, symbol: string, description: string) {
          this.wdId.S = wdId;
          this.symbol.S = symbol;
          this.description.S = description;
      }
  }

您将调用 var inst1 = new Instrument('wdId_A', 'symbol_A', 'desc_A') 创建类对象

希望对您有所帮助

---编辑---

你也可以这样做:

export class Instrument {
  wdId: { S: string };
  description: { S: string };
  symbol: { S: string };

  public constructor(wdId: string, symbol: string, description: string) {
    this.wdId = {S: wdId};
    this.symbol = {S: symbol};
    this.description = {S: description};
  }
}

;)

关于javascript - 无法将 json 数据映射到 js 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47414379/

相关文章:

javascript - 如何通过 JavaScript 中给定的选项卡 ID 将 chrome 选项卡分配给变量?

ruby - 将类的 Ruby 数组转换为 JSON

javascript - 如何让 JQuery 接受 JSON 回复?

javascript - 如何在 React Native 中启用 Android 监视器以检查日志?

javascript - jQuery 数据表列 sum() of hh :mm:ss

javascript - 未捕获( promise ): Error: Cannot match any routes: ' '

TypeScript 仅允许参数中父对象的子项

typescript - 用于检查函数参数可分配性的自定义 TSLint 规则(无双方差)

javascript - div 在页面加载或刷新时加载 css 的问题

ios - 从 url 下载数据时等待填充表格 View