How to join two forms (one is array inside of another)

Viewed 68

I'm having problem joining those two

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".
    };

How to throw the whole response from tasks to projects->other? I have good response when I console.log tasks, but projects just don't have "other" prop and that makes my form invalid.

Forms are made with Angular FormBuilder.

(Just letting you know that in this case using ":" doesn't work - array is not assigned and property "other" is completely skipped in console etc.)

2 Answers

Use spread Operator

This will do the thing you need

let otherObject= {...tasks};

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

Note spread operator starts with '...' and is ES6 feature

I am adding further an example from using browser console ( chrome), This should help to clarify it further.

enter image description here

So one mate raised a point in the comments about having an array in spread in place of single object Below is something you can refer ;) enjoy!!

enter image description here

Adding one more way of doing it using spread operator :

enter image description here

Related