javascript - 如何将嵌套 Typescript 对象的值映射到 JSON 对象的属性
问题描述
在我正在进行的一个项目中,我们使用名为formly的 Angular 库来动态创建表单。
目前,表单配置被硬编码为一个名为mockForm
. 除了属性等于的对象中的属性外,其中的所有属性mockForm
都是硬编码的:options
type
'select'
模拟表格
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: []
}
}
]
}
]
}
]
}
]
};
我想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,其属性是其属性equals的key
值;这些 JSON 属性的值代表表单的下拉选项。mockForm
type
'select'
预期结果应如下所示:
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 调用中填充?)
解决方案
您的 JSON mockForm非常典型。如果它保持不变,那么您必须手动迭代底部叶子,mokeForm.subSections[1].subSections
然后循环到那里以匹配标签和类型。
否则,您需要编写遍历 mokeForm JSON 的 parse 并分配所需的选项是各自的地方。
推荐阅读
- git - Git 显示我添加了另一个人的更改
- sql - 使用 JOB_TITLE 和 EVENT_DATE 查找上次换工作的日期
- c - C中的每个指针都应该分配在堆上吗?
- c - 如何使用 llvm-c API 使用内联汇编
- flutter - 如何用另一个 GestureDetector 包装 GestureDetector 并在任何地方获取事件
- laravel - laravel 雄辩的嵌套关系计数
- node.js - typescript 在 checkAuth 中间件之后更改请求的类型
- javascript - 我在 HTML 中制作的可播放结构很平淡,通用属性没有帮助
- azure - 如何将“存储 Blob 数据读取器”角色分配给 azure 中的用户/组?
- bash - 如果第一行匹配表达式,则删除行,但接下来的 2 行不匹配不同的表达式