Angular14中如何合并两个对象生成动态表单所需新对象?
Angular 14 动态表单配置与内容数组合并方案
注意:你提供的最终结构中selectMenuOptions存在重复键的问题,JavaScript/TypeScript对象不允许重复键,因此以下方案将其调整为数组形式存储对应字段的所有内容值,这也是下拉选择框选项的合理格式。
类型定义
先定义对应的数据类型,确保类型安全:
// 表单配置项类型 interface FormConfig { name: string; type: string; label: string; } // 内容项类型 interface ContentItem { [key: string]: string; } // 合并后的结果类型 interface MergedFormItem { name: string; id: string; label: string; type: string; selectMenuOptions: string[]; }
合并实现函数
在Angular组件中实现数组合并逻辑:
mergeFormConfigAndContent(formConfigs: FormConfig[], contents: ContentItem[]): MergedFormItem[] { return formConfigs.map((config, index) => { // 从内容数组中提取当前配置项对应name的所有值 const options = contents.map(item => item[config.name]); return { name: config.name, id: `CONTENT ${index + 1}`, label: `${config.label.toUpperCase()} ${index + 1}`, type: config.type, selectMenuOptions: options }; }); }
使用示例
将你的配置数组和内容数组传入函数即可得到目标结果:
// 表单配置数组 const formConfigs: FormConfig[] = [ { name: "VALUE1", type: "select", label: "Label" }, { name: "VALUE2", type: "select", label: "Label" }, { name: "VALUE3", type: "select", label: "Label" } ]; // 内容数组 const contents: ContentItem[] = [ { VALUE1: "CONTENT", VALUE2: "CONTENT", VALUE3: "CONTENT", VALUE4: "CONTENT", VALUE5: "CONTENT" }, { VALUE1: "CONTENT", VALUE2: "CONTENT", VALUE3: "CONTENT", VALUE4: "CONTENT", VALUE5: "CONTENT" }, { VALUE1: "CONTENT", VALUE2: "CONTENT", VALUE3: "CONTENT", VALUE4: "CONTENT", VALUE5: "CONTENT" } ]; // 获取合并后的结果 const mergedItems = this.mergeFormConfigAndContent(formConfigs, contents);
代码说明
- 通过
map遍历表单配置数组,同时利用索引生成id和label的序号后缀 - 嵌套
map遍历内容数组,提取每个内容项中对应配置项name字段的值,组成下拉选项数组 - 严格按照需求生成每个合并对象的字段,确保结构匹配
内容的提问来源于stack exchange,提问作者kayza
相关产品推荐
相关产品推荐

