angular - 如何合并两个 json 对象(一个是另一个中的数组)

标签 angular forms angular6 formbuilder

我在加入这两个时遇到问题

let tasks = [];

    this.tasks.map(it => {
        tasks.push(
            {
                'prop1': it['prop1'],
                'prop2': it['prop2'],
                'prop3': it['prop3'],
            }
        );
    });

    let projects = {
        'title': this.projectForm.value['title'],
        'state': this.projectForm.value['state'],
        'comment': this.projectForm.value['comment'],
        'other': 
        // here I want to have the whole "tasks" array with "prop1", "prop2", "prop3".
    };

如何将整个响应从任务扔到项目->其他? 当我 console.log 任务时,我有很好的响应,但项目只是没有“其他” Prop ,这使得我的表单无效。

表单是使用 Angular FormBuilder 制作的。

(只是让您知道,在这种情况下使用“:”不起作用 - 未分配数组并且在控制台等中完全跳过属性“other”。)

最佳答案

使用点差运算符

这将完成您需要的事情

let otherObject= {...tasks};

let projects= {'other': {...otherObject}, 'title': this.projectForm.value['title'],
        'state': this.projectForm.value['state'],
        'comment': this.projectForm.value['comment']
    }

注意扩展运算符以“...”开头,是 ES6 功能

我将进一步添加一个使用浏览器控制台(chrome)的示例,这应该有助于进一步澄清。

enter image description here

因此,一位伙伴在评论中提出了一个观点,即用数组代替单个对象 以下是您可以引用的内容;)享受吧!!

enter image description here

使用展开运算符添加另一种方法:

enter image description here

关于angular - 如何合并两个 json 对象(一个是另一个中的数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54196191/

相关文章:

twitter-bootstrap - Angular 2下拉列表中的bootstrap 4不起作用

angularjs - 如何通过实际更改模型将表单设置为 $dirty?

html - 使用 perl LWP lib 传递表单数据时遇到问题

angular - node_modules/@types/pdfjs-dist/index.d.ts(63,39) : error TS2304: Cannot find name 'unknown' 中的错误

javascript - 通知 Angular 2 应用程序初始化错误

angular - 如何在 angular2 中将事件从 app.component 广播到路由器导出

jquery - 选择带有 'Other' 选项的框以显示输入文本字段。如何使用 jquery 获取表单提交的值?

ckeditor - 一页中有多个 CKEditor5 - 性能问题

angular - 使用自定义配置运行 ng build

angular - IONIC 2 构建错误 : "ngc: Error: Error Cannot write file ...[myProject]/.tmp/[some folder]/*.d.ts"