gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:58:14 26 4
gpt4 key购买 nike

我正在尝试将 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com