I am new to JavaScript. I need to map a YAML file to Interface in Javascript. I have a YAML file which is like the below:
- provider_name: SEA-AD
consortiumn_name: SEA-AD
defaults: thumbnail
Donors:
- id: "https://portal.brain-map.org/explore/seattle-alzheimers-disease#Human-MTG-10x_SEA-AD_Male_TissueBlock"
label: Registered 2/20/2023, Rebecca Hodge, SEA-AD
description: "4 x 4 x 5 millimeter, 0.11 millimeter"
link: "https://portal.brain-map.org/explore/seattle-alzheimers-disease"
sex: Male
Blocks:
- id: https://portal.brain-map.org/explore/seattle-alzheimers-disease#Human-MTG-10x_SEA-AD_Male_TissueBlock
label: Registered 2/20/2023, Rebecca Hodge, SEA-AD
And an interface in typescript which is:
export interface Provider {
provider_name: string;
provider_uuid: string;
consortium_name: string;
defaults: string;
donors: Donor[]
}
export interface Donor {
id: string;
label: string;
description: string;
link: string;
age: number;
sex: string;
bmi: number;
blocks: Block[];
}
export interface Block {
id: string;
label: string;
}
Now I want to map the interface with the TypeScript file in JavaScript.
So far, I am unable to map the inner variables (Like the Donors in YAML file). I have done following:
cosnt data = load("YAML File");
const provider = {
provider_name : data.provider_name,
consortium_name : data.consortium_name,
dafaults: data.defaults,
donors: data.Donors.map(function (donor ) {
I am new to JavaScript. Am I doing it right? Is there any other way to do this?? The map function is not available in JavaScript. Any leads or references will be appreciated. Thanks!
2
Answers
What you want is to read-in your yaml file as a js object.
You could use packages like
js-yaml
:npm install js-yaml -g
.You merge objects like this:
The objects already are json objects.
This is not TypeScript. But it is just to show the strategy.
You could validate the loaded YAML is in the correct JSON format using something like AJV, and have it cast the data to your type:
You could also just cast it. Something like this: