How to insert data into an array position

Asked

Viewed 119 times

0

I have a function salvar that creates an array and sends the data via post to the BD, but before sending the data I need to insert data into two positions of the array.

I’ve tried with array_fill and array_splice but I’m stuck on that part. Someone could help?

The code is this:

$('#salvar').on('click', function (e) {

var formSerialize = $('#form').serializeArray();
//formSerialize_splice( $formSerialize, 11, 0, formSerialize('#id_servidor') );
//formSerialize = array_fill_keys ('id_origem','id_servidor');

console.log(formSerialize);

var isValid = $('#form').valid();

if (!isValid) {
    msgValidateForm();
} else {

    var formJson = {};

    $.map(formSerialize, function(n, i){
        formJson[n['name']] = n['value'];
    });

    $.ajax({
        url: window.location.origin + "/cadServidores_db.php?action=salvar",
        type: 'POST',
        data: formJson,
        success: function()
        {
            dialogCreateSuccess(formJson.id_servidor);
        }
    });

}

return isValid;

});

And the return is getting like this:

0: Object { name: "id_servidor", value: "1102778" }
​
1: Object { name: "nm_servidor", value: "vair" }
​
2: Object { name: "dt_admissao", value: "2019-06-03" }
​
3: Object { name: "dt_nascimento", value: "1917-09-27" }
​
4: Object { name: "nr_cpf", value: "12345678945" }
​
5: Object { name: " lotacao", value: "E305" }
​
6: Object { name: "nm_categoria", value: "COM" }
​
7: Object { name: "nm_cargoGratificado", value: "supervisor" }
​
8: Object { name: "id_cargo", value: "18" }
​
9: Object { name: "fl_ativo", value: "1" }
​
10: Object { name: "id_original", value: "" }
​
11: Object { name: "id_origem", value: "" }
​
length: 12

How do I insert data at positions 10 and 11?

  • Is the console.log(formSerialize); that shows this data? What kind of data you want to insert?

1 answer

3

Use the method .find() to fetch the object by the key value name and change the value of the key value of the same object:

formSerialize.find(x => x.name == 'id_original').value = "valor que vc quer inserir";
formSerialize.find(x => x.name == 'id_origem').value = "valor que vc quer inserir";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.