I have a file JSON and I would like to retrieve the datas for the fields label
and svm
.
Here is the file JSON. The fields label
and svm
are into PORTFOLIO > REGROUPEMENT > ELEMENT
I have tried to display the datas via the GoogleChrome console.
getTitles(mode: PortfolioModeEnum): void {
this.portfolioValue = 0;
this.lines = [];
this.service.getPortfolios(mode).pipe(
takeUntil(this.unsubscribe$)
).subscribe((res: any) => {
if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {
console.log("Test => " res.REGROUPEMENT[0].ELEMENT[0]);
}
});
}
I have an error message:
core.mjs:6484 ERROR TypeError: Cannot read properties of undefined (reading '0')
I don't know how to retrieve my data on a nested loop? I want to retrieve LABEL
and SVM
, please.
portfolio.response.ts
export interface PortfolioResponse extends ApiResponse {
PORTFOLIO: {
VALPTF: number;
DETAILS: {
ACCOUNTLAB: string;
ACCOUNTTYPE: string;
LABEL: string;
ACCOUNTPHYSICAL: string;
};
REGROUPEMENT: InstrumentRegroupement[];
}
}
export interface InstrumentRegroupement {
TYPEVALUE: number;
ASSETCATLABEL: string;
CURRENCY: string;
AMOUNT: number;
PERCENTAGE: number;
ELEMENT: {
LABEL: string;
STOCK: string;
SVM: number;
COUPONNUMBER: number;
ISINCODE: string;
MARKETPLACE: string;
TYPEVALUE: number;
ASSETCATLABEL: string;
INSTRCURRENCY: string;
AVERAGEDPRICE: number;
QUANTITY: number;
LASTPRICE: number;
CURRENCYVALO: string;
PRICEVARIATION: number;
CAPITALGAINLOSS: number;
ACCRUEDINTERESTS: number;
VALORIZATION: number;
VALORIZATIONEUR: number;
DIFFER: number;
DIFFEREUR: number;
PERCENTAGE: number;
BLOCKCATEGORY: string;
BLOCKQUANTITY: number;
AVALLOWED: string;
PLACECODE: number;
PLACELABEL: string;
SECURITYPRICEVARIATIONPRC: number;
SECURITYPRICEVARIATIONNOM: number;
INITIALPURCHASEDATE: string;
NOTATION: string;
NBRORDRENOTE: number;
PERFACHAT: number;
REGROUP: number;
}[];
sort: { by: PortfolioSortEnum, dir: '' | 'asc' | 'desc' };
showLine: boolean;
}
EDIT
EDIT 2
TS
getTitles(mode: PortfolioModeEnum): void {
this.portfolioValue = 0;
this.lines = [];
this.service.getPortfolios(mode).pipe(
takeUntil(this.unsubscribe$)
).subscribe((res: any) => {
if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {
const data = res.PORTFOLIO.REGROUPEMENT.map((regroupment) => {
return regroupment.ELEMENT.map((element) => ({
label: element.LABEL,
svm: element.SVM,
}));
}).flat();
}
});
}
HTML
Thank you for your help.
CodePudding user response:
If you simply need a list of the label
and svm
fields without needing details of the rest of the hierarchy, you could use array.map()
to exact the keys you need at each level, then use array.flat()
to flatten the structure.
const data = res.PORTFOLIO.REGROUPEMENT.map((regroupment) => {
return regroupment.ELEMENT.map((element) => ({
label: element.LABEL,
svm: element.SVM,
}));
}).flat();