【发布时间】:2021-07-14 18:13:42
【问题描述】:
在我正在进行的一个项目中,我们使用名为 formly 的 Angular 库来动态创建表单。
目前,表单配置被硬编码为一个名为 mockForm 的 Typescript 对象。除了type 属性等于'select' 的对象中的options 属性之外,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 返回
{
"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,其属性是来自 mockForm 的 key 值,其属性 type 等于 'select';而这些 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?我需要手动遍历@987654336 @ 以便从 API 调用中填充?)
【问题讨论】:
-
您可能正在使用 TypeScript,但这似乎不是特定于 TypeScript 的。对我来说,这更像是一个 JavaScript 问题。也许你应该添加 JavaScript 标签?
标签: javascript json typescript object nested-object