Tenzolinho
Tenzolinho

Reputation: 982

Push into array overrides previous value

I want to build an array having this format:

x = [
      {'projectName': 'a', 'serialNo': 1},
      {'projectName': 'b', 'serialNo': 2},
      {'projectName': 'c', 'serialNo': 3},
]

using values passed from a form

onSubmit(form: NgForm) {
    let x = []
    x.push({
      projectName: form.value.projectName,
      serialNo: form.value.serialNo,
    })

    console.log(x) // -> this will always give me the value I just inserted

    // form.value.project = JSON.stringify(x)
    // putObj(form.value).subscribe((res) => { });
}

Then I send form.value in backend and the field project is modified. My problem is that everytime I push values into x, the previous value overrides.

Which seems to be the problem? If my code is unclear, I can explain or give more snippets.

EDIT: thank you very much! It worked, I declared x inside component.

Upvotes: 0

Views: 1426

Answers (4)

suraj13k
suraj13k

Reputation: 416

let x = [] //declare outside

onSubmit(form: NgForm) {

    x.push({
      projectName: form.value.projectName,
      serialNo: form.value.serialNo,
    })

}

Upvotes: 3

MojioMS
MojioMS

Reputation: 1693

remove the

let x = []

you can define your array with initial elements within ur onInit method in your component, such as:

type x = Array<{projectName: string, serialNo: number}>;

ngOnInit() { 
    this.x = [
        {'projectName': 'a', 'serialNo': 1},
        {'projectName': 'b', 'serialNo': 2},
        {'projectName': 'c', 'serialNo': 3}, 
    ]
}

onSubmit(form: NgForm) {
    this.x.push({
        projectName: form.value.projectName,
        serialNo: form.value.serialNo,
    })
}

Upvotes: 1

Kate
Kate

Reputation: 61

Yeap, move your let x = [] outside of function. Not sure what you are planning to do, it might need to be a global variable. Every time you enter the function you set x to be an empty array.

Upvotes: 1

mtizziani
mtizziani

Reputation: 1016

not tested, but should work in theory:

// ...
private x: {'projectName': string, 'serialNo':number}[] = [];
// ...
onSubmit(form: NgForm) {
    this.x.push({
      projectName: form.value.projectName,
      serialNo: form.value.serialNo,
    });

    console.log(this.x)
}
// ...

Upvotes: 1

Related Questions