如何将嵌套Typescript对象的值映射到JSON对象的属性



在我正在进行的一个项目中,我们使用名为formly的Angular库来动态创建表单。

目前,表单配置被硬编码为一个名为mockForm的Typescript对象。除了type属性等于'select':的对象中的options属性之外,mockForm中的所有属性都是硬编码的

mockForm

export const mockForm = {
name: 'root',
subSections: [
{
name: 'Client',
subSections: [
{
name: 'Contact Information'
},
{
name: 'Insurance Information'
}
]
},
{
name: 'Sales',
subSections: [
{
name: 'Overview',
subSections: [
{
name: 'Overview - A',
fields: [
{
key: 'fieldA1',
type: 'input',
templateOptions: {
label: 'A1',
required: true
}
},
{
key: 'fieldA2',
type: 'select',
templateOptions: {
label: 'A2',
required: true,
options: []
}
}
]
},
{
name: 'Overview - B',
fields: [
{
key: 'fieldB1',
type: 'input',
templateOptions: {
label: 'B1',
required: false
}
},
{
key: 'fieldB2',
type: 'select',
templateOptions: {
label: 'B2',
required: false,
options: []
}
}
]
}
]
}
]
}
]
};

我想通过使用调用的API来填充options属性,该API返回以下对象:

API返回

{
"multi_value_fields": {
"fieldA2": [
"froodian@outlook.com",
"gastown@sbcglobal.net",
"dgriffith@me.com",
"maradine@live.com",
"samavati@icloud.com",
"naupa@comcast.net"
],
"fieldB2": [
"<3m",
"<6m",
"<9m",
"<12m",
"+12m",
"N/A"
]
}
}

API调用返回的对象返回一个JSON,其属性为type等于'select'mockFormkey值;并且这些JSON属性的值表示表单的下拉选项。

预期结果应如下:

export const mockForm = {
name: 'root',
subSections: [
{
name: 'Client',
subSections: [
{
name: 'Contact Information'
},
{
name: 'Insurance Information'
}
]
},
{
name: 'Sales',
subSections: [
{
name: 'Overview',
subSections: [
{
name: 'Overview - A',
fields: [
{
key: 'fieldA1',
type: 'input',
templateOptions: {
label: 'A1',
required: true
}
},
{
key: 'fieldA2',
type: 'select',
templateOptions: {
label: 'A2',
required: true,
options: [
"froodian@outlook.com",
"gastown@sbcglobal.net",
"dgriffith@me.com",
"maradine@live.com",
"samavati@icloud.com",
"naupa@comcast.net"
]
}
}
]
},
{
name: 'Overview - B',
fields: [
{
key: 'fieldB1',
type: 'input',
templateOptions: {
label: 'B1',
required: false
}
},
{
key: 'fieldB2',
type: 'select',
templateOptions: {
label: 'B2',
required: false,
options: [
"<3m",
"<6m",
"<9m",
"<12m",
"+12m",
"N/A"
]
}
}
]
}
]
}
]
}
]
};

我还没有经历过这样的场景,我不太确定如何处理(我应该从JSON属性开始并映射回mockForm吗?我需要手动迭代mockForm才能从API调用进行填充吗?(

您的JSONmockForm非常典型。如果它保持不变,则必须手动迭代底部叶,即mokeForm.subSections[1].subSections,然后在那里循环以匹配标签&类型

否则,您需要编写在mokeForm JSON&指定所需选项是各自的位置。

最新更新