我正在尝试将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;
}
}
答案 0 :(得分:1)
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')
创建一个类对象
希望这有帮助
--- --- EDIT
你也可以这样做:
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};
}
}
)